Java Software Engineer

  Home  Java Programing  Java Software Engineer


“Java Software Engineer based Frequently Asked Questions in various Java Software Engineer job interviews by interviewer. These professional questions are here to ensures that you offer a perfect answers posed to you. So get preparation for your new job hunting”



45 Java Software Engineer Questions And Answers

21⟩ Can you compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other?

sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

wait(), on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.

sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll(), to achieve synchronization and avoid race conditions.

 180 views

22⟩ Tell me public static void main(String args[])?

☛ public : Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.

☛ static : It is a keyword in java which identifies it is class based i.e it can be accessed without creating the instance of a Class.

☛ void : It is the return type of the method. Void defines the method which will not return any value.

☛ main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.

☛ String args[] : It is the parameter passed to the main method.

 133 views

23⟩ Tell us what is the Java Classloader? List and explain the purpose of the three types of class loaders?

The Java Classloader is the part of the Java runtime environment that loads classes on demand (lazy loading) into the JVM (Java Virtual Machine). Classes may be loaded from the local file system, a remote file system, or even the web.

When the JVM is started, three class loaders are used:

1. Bootstrap Classloader: Loads core java API file rt.jar from folder.

2. Extension Classloader: Loads jar files from folder.

3. System/Application Classloader: Loads jar files from path specified in the CLASSPATH environment variable.

 148 views

24⟩ How to override a private or static method in Java?

You cannot override a private or static method in Java. If you create a similar method with same return type and same method arguments in child class then it will hide the super class method; this is known as method hiding. Similarly, you cannot override a private method in sub class because it’s not accessible there. What you can do is create another private method with the same name in the child class. Let’s take a look at the example below to understand it better.

class Base {

private static void display() {

System.out.println("Static or class method from Base");

}

public void print() {

System.out.println("Non-static or instance method from Base");

}

class Derived extends Base {

private static void display() {

System.out.println("Static or class method from Derived");

}

public void print() {

System.out.println("Non-static or instance method from Derived");

}

public class test {

public static void main(String args[])

{

Base obj= new Derived();

obj1.display();

obj1.print();

}

}

 128 views

25⟩ Tell me what are static initializers and when would you use them?

A static initializer gives you the opportunity to run code during the initial loading of a class and it guarantees that this code will only run once and will finish running before your class can be accessed in any way.

They are useful for performing initialization of complex static objects or to register a type with a static registry, as JDBC drivers do.

Suppose you want to create a static, immutable Map containing some feature flags. Java doesn’t have a good one-liner for initializing maps, so you can use static initializers instead:

public static final Map<String, Boolean> FEATURE_FLAGS;

static {

Map<String, Boolean> flags = new HashMap<>();

flags.put("frustrate-users", false);

flags.put("reticulate-splines", true);

flags.put(...);

FEATURE_FLAGS = Collections.unmodifiableMap(flags);

}

Within the same class, you can repeat this pattern of declaring a static field and immediately initializing it, since multiple static initializers are allowed.

 134 views

26⟩ Explain me how can you catch an exception thrown by another thread in Java?

This can be done using Thread.UncaughtExceptionHandler.

Here’s a simple example:

// create our uncaught exception handler

Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {

public void uncaughtException(Thread th, Throwable ex) {

System.out.println("Uncaught exception: " + ex);

}

};

// create another thread

Thread otherThread = new Thread() {

public void run() {

System.out.println("Sleeping ...");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println("Interrupted.");

}

System.out.println("Throwing exception ...");

throw new RuntimeException();

}

};

// set our uncaught exception handler as the one to be used when the new thread

// throws an uncaught exception

otherThread.setUncaughtExceptionHandler(handler);

// start the other thread - our uncaught exception handler will be invoked when

// the other thread throws an uncaught exception

otherThread.start();

 124 views

28⟩ As you know ArrayList, LinkedList, and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of?

Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC.

 167 views

29⟩ Please explain what is the ThreadLocal class? How and why would you use it?

A single ThreadLocal instance can store different values for each thread independently. Each thread that accesses the get() or set() method of a ThreadLocal instance is accessing its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or transaction ID). The example below, from the ThreadLocal Javadoc, generates unique identifiers local to each thread. A thread’s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

public class ThreadId {

// Next thread ID to be assigned

private static final AtomicInteger nextId = new AtomicInteger(0);

// Thread local variable containing each thread's ID

private static final ThreadLocal<Integer> threadId =

new ThreadLocal<Integer>() {

@Override protected Integer initialValue() {

return nextId.getAndIncrement();

}

};

// Returns the current thread's unique ID, assigning it if necessary

public static int get() {

return threadId.get();

}

}

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

 113 views

30⟩ Tell me what is multiple inheritance? Is it supported by Java?

If a child class inherits the property from multiple classes is known as multiple inheritance. Java does not allow to extend multiple classes.

The problem with multiple inheritance is that if multiple parent classes have a same method name, then at runtime it becomes difficult for the compiler to decide which method to execute from the child class.

Therefore, Java doesn’t support multiple inheritance. The problem is commonly referred as Diamond Problem.

 143 views

31⟩ Tell me what is reflection? Give an example of functionality that can only be implemented using reflection?

Reflection allows programmatic access to information about a Java program’s types. Commonly used information includes: methods and fields available on a class, interfaces implemented by a class, and the runtime-retained annotations on classes, fields and methods.

Examples given are likely to include:

☛ Annotation-based serialization libraries often map class fields to JSON keys or XML elements (using annotations). These libraries need reflection to inspect those fields and their annotations and also to access the values during serialization.

☛ Model-View-Controller frameworks call controller methods based on routing rules. These frameworks must use reflection to find a method corresponding to an action name, check that its signature conforms to what the framework expects (e.g. takes a Request object, returns a Response), and finally, invoke the method.

☛ Dependency injection frameworks lean heavily on reflection. They use it to instantiate arbitrary beans for injection, check fields for annotations such as @Inject to discover if they require injection of a bean, and also to set those values.

☛ Object-relational mappers such as Hibernate use reflection to map database columns to fields or getter/setter pairs of a class, and can go as far as to infer table and column names by reading class and getter names, respectively.

 134 views

32⟩ Tell us what is the difference between equals() and == ?

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.

“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.

 130 views

33⟩ Tell me why is the code printing true in the second and false in the first case?

JVM’s cache behavior can be confusing, so this question tests that concept. The second output is true as we are comparing the references, because the JVM tries to save memory when the Integer falls within a range (from -128 to 127). At point 2, no new reference of type Integer is created for ‘d’. Instead of creating a new object for the Integer type reference variable ‘d’, it is only assigned with a previously created object referenced by ‘c’. All of these are done by JVM.

 128 views

36⟩ Please explain and compare fail-fast and fail-safe iterators. Give examples?

The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.

Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException. Some examples include ArrayList, HashSet, and HashMap (most JDK1.4 collections are implemented to be fail-fast).

Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList.

 135 views

37⟩ Do you know why Java is platform independent?

Platform independent practically means “write once run anywhere”. Java is called so because of its byte codes which can run on any system irrespective of its underlying operating system.

 133 views

38⟩ Explain me when do you use volatile variables?

When a member variable is accessed by multiple threads and want the value of a volatile field to be visible to all readers (other threads in particular) after a write operation completes on it.

 142 views

39⟩ Explain me how are Annotations better than a Marker Interfaces?

Annotations lets one achieve the same purpose of conveying metadata about the class to its consumers without creating a separate type for it. Annotations are more powerful, too, letting programmers pass more sophisticated information to classes that “consume” it.

 139 views