Top Java Developer Interview Questions and Answers

5.00 avg. rating (98% score) - 4 votes

Java is a set of multiple computer software and specifications. It is used for application software development and also works for the cross-platform environment. Java developers can run all codes in any platform without the need for recollection with the help of Write-Once-Run-Anywhere (WORA). Java is one of the most preferred platforms for developing a variety of applications for smartphones and other devices. It is also used for creating corporate-specific tooling.


Java developers perform multiple tasks throughout the development cycle of applications.  They are responsible for conceptual queries, design parts, and testing phases to implement and maintain application software.


Q1. How is queue implemented in Java?


Ans. A queue is known as the linear data structure similar to the stack data structure. It is an interface available in java.util package and used to store the elements with insertion and deletion operations. In this process, the first element is inserted from the one end called REAR (Tail), and the existing element is deleted from the other end called FRONT (Head). The whole operation of queue implementation is known as FIFO (First in first out).


Q2. Explain the difference between the Runnable and Callable interface in Java.


Ans. Following are the differences between the Runnable and Callable interface in Java:


RunnableCallable
Existence and availabilityIt exists in java from the beginning, i.e. JDK 1.0.It does not exist from the beginning. Added in Java 5.
Checked ExceptionThe call () method in Runnable can throw Checked Exception.The run () method cannot throw any Checked Exception.
ResultIt can return the result of the parallel processing of a task.


Example:


Runnable’s run()

It cannot return any result for the task.


 

Call () vs run () methodsIn Runnable interface, we need to override run () method.In the Callable interface, we need to override call () method.
ExecutionRunnable instance cannot be passed at the time of callable interface.Executorservice interface is used to execute the callable interface.

 


Q3. Explain the implementation of Binary Tree in Java?


Ans. A binary tree is a linear data structure similar as stack, queue, and lists. It consists of two children in a parent node.


class Node {


int val;


Node left;


Node right;


Node(int val) {


this.val = val;


right = null;


left = null;


}


}


By following below code, we can add starting node (Root) of the binary tree:


public class BinaryTree {


Node root;


// …


}


Q4. What is the Executor Framework in Java? How is it different from the Fork Join Framework?


Ans. The Executor framework is used to manage various threads with the help of a group of components. It is used to run the runnable objects without building new threads and use the existing threads.


Example:


public class Test implements Runnable


{


private String message;


public Test(String message)


{


this.message = message;


}


@Override public String run() throws Exception


{


return “Hey ” + message + “!”;


}


}


Executor Framework is different from the Fork Join Framework:


Fork Join Framework is created to execute ForkJoinTask. It is the lighter version of FutureTask, whereas Executor Framework is created to offer a thread pool that executes the offered task with the use of multiple pooled threads.


There are some ThreadPoolExecutor accessible by JDK API, which is a tread pool of the background thread. Executors.newCachedThreadPool is an unbounded thread used to spawn new threads and reclaim old threads


Q5. What is thread-safety in Java? How do you achieve it?


Ans. Java provides a multi-threaded environment, multiple threads are created from the same object share object variable, and it will cause data inconsistency when threads are used to update and read shared data. JVM helps in improving the performance of applications by running bytecode in different worker threads.


Different methodologies to achieve thread-safety:


  • Stateless implements
  • Synchronized collections
  • Thread-Local Fields
  • Atomic objects
  • Concurrent collections
  • Immutable implementations


Q6. Explain the difference between == and equals?


Ans. There are two important differences between == and equals are:


  • == never throws NullPointerException


enum1 Color { RED, BLUE };


Color nothing = null;


if (nothing == Color.RED);      // runs fine


if (nothing.equals(Color.RED)); // throws NullPointerEx


  • == is subject to type compatibility check at the compile time


enum1 Color { RED, BLUE};


enum1 Chiral { LEFT, RIGHT };


if (Color.RED.equals(Chiral.LEFT)); // compiles fine


if (Color.RED == Chiral.LEFT);      // DOESN’T COMPILE!!! Incompatible types!


 


Q7. How to avoid ConcurrentModificationException?


Ans. We can avoid the Exception by using Iterator and call remove():


Iterator<String> iter1 = myArrayList.iterator();


while (iter1.hasNext()) { String str = iter1.next();


if (someCondition) iter1.remove(); }


Q8. Explain the difference between poll() and remove() method of a Queue interface in Java?


Ans. Following are the difference between poll() and remove() method:


Poll()Remove()
●       poll() method is available in java.util.package


●       It is used to retrieve the first element of the queue


●       If the queue is empty, it will return null and does not throw an exception


●       The syntax of the method is:


public PriorityQueue poll(){


}

●       remove() method is also available in java.util.package


●       It is used to remove the first element of the queue


●       If the queue is empty, it will throw an exception NoSuchElementFoundException but it will not return a null value


●       The syntax of the method is:


public boolean remove(){}


 


Q9. Does A class inherit constructors of its superclass in Java programming?


Ans. No, A class does not inherit constructs of its superclass


Q10. How are the elements of a Gridbaglayout arranged in Java programming?


Ans. In Gridbaglayout, elements are arranged in the form of a grid, whereas elements are present in different sizes and occupy the space according to their sizes. It can cover one or more rows and columns of various sizes.


Q11. What is the difference between Concurrent Collections different from Synchronized Collections?


Ans. Concurrent collection and synchronized collection are used for thread safety. The difference between them is how they achieve thread-safety by their scalability, performance. The performance of concurrent collection is better than the synchronized collection as it holds the single portion of the map to attain concurrency.


Q12. What is CopyOnWriteArrayList? How is it different from ArrayList and Vector?


Ans. CopyOnWriteArrayList is used to implement a list interface in the array list. It is a tread safe variant implemented for creating a new copy of the existing arrays.


ArrayList has a synchronized collection, whereas CopyOnWriteArrayList has a concurrent collection.


Q13. When we use Serializable vs. Externalization interface?


Ans. Following are the difference between Serializable and Externalization:


SerializableExternalization
●       It is a marker interface and does not contain any method


●       Default serializable is easy to implement and sometimes it comes with an issue


●       It does not call any class constructor

●       It is defined as the child interface of Serializable. It contains two methods i.e. writeExternal() and readExternal()


●       It will provide better performance with serialization logic that has to be written by the programmer


●       We can use Externalization with a public no-arg constructor


 


Q14. What advantage does the java layout manager offer over the traditional windowing system?


Ans. Java uses layout manager to lay out components across all windowing platform. They do not have consistent sizing and positioning so that they can provide platform-specific differences among the windowing system.


Q15. Explain map interface in Java programming?


Ans. A map is an object used for mapping between a key and a value. It does not contain the duplicate key, and each key can map to one value. A map interface is not a subtype of the collection interface. So it acts differently from other collection types.


Q16. Which Classes Of Exceptions May Be Caught By A Catch Clause In Java Programming?


Ans. A catch clause can catch any exception that is assigned to the throwable type, including the error and exception types.


Q17. What do three dots in the method parameters mean? What do the three dots in the following method mean?


public void Method_N(String… strings){


// method body


}


Ans. The given code describes that it can receive multiple String arguments.


Syntax:


Method_N(“foo”, “bar”);


Method_N(“foo”, “bar”, “baz”);


Method_N(new String[]{“foo”, “var”, “baz”});


We can use the String var as an array:


public void Method_N(String… strings){


for(String whatever: strings){


// do whatever you want


}


// the code above is is equivalent to


for( int j = 0; i < strings.length; j++){


// classical for. In this case, you use strings[i]


}


}


Q18. Name the Container Method Used To Cause Container To Be Laid Out And Redisplayed In Java Programming?


Ans.validate()’ Container method is used to cause a container to be laid out and redisplayed in Java Programming.


Q19. What is reflection in Java programming? Why is it useful?


Ans. It is used to describe code that is used to inspect other code in the same system and make it dynamic and tied together at runtime.


Example: If you want to call a ‘doSomething’ method in java on an unknown type object. Java static system does not support this until the object confirms a known interface. If you are using reflection, then it takes your code to the object, and it will find the method ‘doSomething.’ After that, we can call the method whenever we want.


Method method_N = foo.getClass().getMethod(“doSomething”, null);


method_N .invoke(foo, null);


Q20. What is the objective of the Wait(), Notify(), And Notifyall() methods in Java programming?


Ans. In Java programming, the wait(), notify(), and notifyAll() methods are used to provide a systematic way for threads to communicate with each other.


About the Author

Bhumika Yadav

Bhumika Yadav

Bhumika Yadav is a veteran technical content writer and strategist. She has a strong knack on technology and programming. With a specialized degree in Computer Science and Technology. Her way of delivering technical articles in an inventive style is what makes her exclusive. When not writing, she likes to paint, travel, and read fashion publications.
Topics : Web Development