Java is a popular programming language and computing platform. It is used for application software development and also works for the cross-platform environment. Over 15 billion devices worldwide use Java for their software development, thus, there are many job opportunities available for Java Developers. If you are preparing for your next Java interview, then here are the top Java Developer Interview questions and answers to help you boost your interview preparation. 

Brief Introduction Java 

Java is a class-based and object-oriented programming language. Java developers can run all codes in any platform without the need for recollection with the help of Write-Once-Run-Anywhere (WORA). It 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.

Top Java Developer Interview Questions

Q1. How is the 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:

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


Runnable’s run()

It cannot return any result for the task.


Call () vs run () methods In Runnable interface, we need to override run () method. In the Callable interface, we need to override call () method.
Execution Runnable 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 the starting node (Root) of the binary tree:

public class BinaryTree {

Node root;

// …


Also Read>> Top Core Java Interview Questions and Answers 

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.


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 =;

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 the poll() and remove() method:

Poll() Remove()
  1. poll() method is available in java.util.package
  2. It is used to retrieve the first element of the queue
  3. If the queue is empty, it will return null and does not throw an exception
  4. The syntax of the method is:

public PriorityQueue poll(){


  1. remove() method is also available in java.util.package
  2. remove() is used to remove the first element of the queue
  3. If the queue is empty, it will throw an exception NoSuchElementFoundException but it will not return a null value
  4. 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 the Serializable vs. Externalization interface?

Ans. Following are the difference between Serializable and Externalization:

Serializable Externalization
  1. It is a marker interface and does not contain any method
  2. Default serializable is easy to implement and sometimes it comes with an issue
  3. It does not call any class constructor
  1. It is defined as the child interface of Serializable and contains two methods i.e. writeExternal() and readExternal()
  2. Externalization will provide better performance with serialization logic that has to be written by the programmer
  3. 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 a layout manager to layout 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.

Also Read>> Top JavaScript Interview Questions And Answers For 2019-2020

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.


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 a 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.

Q21. Explain the access modifiers in Java. 

Ans. Access modifiers are the keywords that specify the accessibility of a field, class, method, constructor, and other members. 

There are four access modifiers in Java:

  • Public: The class, method, or other members defined as Public can be accessed by any class or method.
  • Protected: The access level is within the package and outside the package through child class.
  • Default: The access level is only within the package. 
  • Private: This can be accessed within the class only.

Q22. What are the three types of loops in Java?

Ans. In Java, Loops execute a set of statements or a block repeatedly until a particular condition is satisfied. The three types of Loops in Java are:

  • For Loops

For loops execute statements repeatedly for a given number of times. These are used when the number of times to execute the statements is known to the programmer.

  • While Loops

It is used when certain statements need to be executed repeatedly until a condition is fulfilled. The condition is checked first before the execution of statements.

  • Do While Loops

It is the same as the While loop with a difference that condition is checked after execution of a block of statements. Thus, statements are executed at least once.

Q23. How to generate random numbers in Java?

Ans. We can generate random numbers in Java using the following: 

  • Math.random method 
  • java.util.Random class
  • ThreadLocalRandom class

Q24. What is the significance of Java packages?

Ans: A Java Package is a set of classes and interfaces are bundled together in a way that they are related to each other. Java Packages provide multiple benefits, such as protection against name collisions; help organize source code; hide implementation for multiple classes; make searching/locating and usage of classes, control access, and annotations easy.

Q25. When we should use serialization?

Ans. Serialization is used when data is transmitted over the network. Serialization enables us to save the object state and convert it into a byte stream that can be sent over the network.  When the byte stream transfers over the network, the object is re-created at the destination.

Q26. Explain multithreading in Java.

Ans: Multithreading is a programming feature that allows multiple tasks to run simultaneously within a single program. In simple terms, it enables concurrent execution of two or more parts of a program for maximum utilization of CPU. Each program is called a thread. In Java, threads are light-weight processes within a process. They run in parallel and help in the performance improvement of any program.

Q27. How can you implement multithreading in Java?

Ans. We can implement multithreading in Java by using the following:

  • By implementing the Runnableinterface.
  • By writing a class that extends Java.Lang.Thread class.

Q28. How to restrict inheritance for a class?

Ans. We can restrict inheritance for a class by:

  • Using the final keyword
  • Making a constructor private
  • Using the Javadoc comment (” // “)
  • Making all methods final, so that we cannot override them

Q29. Explain JSON. 

Ans. JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that is used as an alternative to XML. It is language independent and is easy to understand. JSON uses JavaScript syntax, but its format is text only. The text can be read and used as a data format by any programming language.

Q30. What are the advantages of JSON over XML?

Ans. The advantages of JSON are:

  • JSON is lighter and faster. The XML software parsing process can take a long time.
  • The structure of JSON is straightforward, readable, and easily understandable.
  • JSON objects and code objects match, enabling us to quickly create domain objects in dynamic languages. 
  • JSON uses a map data structure unlike the tree structure in XML.
  • While JSON supports multiple data types—string, number, array, or Boolean – XML data are all strings.

Also Read>> Top Java Interview Questions and Answers

Q31. Name some methods of an object class.

Ans. Methods of an object class are: 

  • clone(): Create and returns a copy of an object
  • equals(): Compares the equality of two objects
  • hashCode(): Returns a hash code value for the object
  • getClass(): Returns the runtime class of the object
  • finalize(): It is called by the garbage collector on the object
  • toString(): Returns a string representation of the object
  • notify(), notifyAll(), and wait(): Synchronize the activities of the independently running threads in a program

Q32. Explain the different states of a thread.

Ans: The different states of a thread are:

  • Ready State: A thread is created.
  • Running State: Thread currently being executed.
  • Waiting State: A thread waiting for another thread to free certain resources.
  • Dead State: A thread that has gone dead after execution.

Q33. Name the two environment variables that must be set to run any Java program.

Ans: PATH variable and CLASSPATH variable are the two environment variables that must be set to run any Java program. 

  • The PATH environment variable is used to specify the set of directories that contains execution programs.
  • The CLASSPATH environment variable specifies the location of the classes and packages.

Q34. What are the types of statements supported by JDBC?

Ans. The different types of statements supported by JDBC:

  • Statement: Executes static queries and for general access to the database
  • CallableStatement: Offers access to stored procedures and runtime parameters
  • PreparedStatement: Provides input parameters to queries when they are executing

Q35. Which Swing methods are thread-safe?

Ans. The thread-safe Swing methods are:

  • Repaint
  • Revalidate
  • Invalidate

Q36. Explain NullPointerException.

Ans. NullPointerException in Java is a RuntimeException. A special null value can be assigned to an object reference in Java. NullPointerException is thrown when a program attempts an object reference with the null value.

Null Pointer Exception is thrown in specific scenarios like:

  •   Method invoked using a null object.
  • Accessing or modifying a null object’s field.
  •  When a null object is passed as an argument to a method
  • Taking the length of a null array.
  • Accessing or modifying the slots of a null array.
  •  Throwing a null object.
  • Synchronizing a null object.

Q37. How can you avoid NullPointerException in Java?

Ans. We can avoid NullPointerException by the following:

  •  Use valueOf() over toString() where both return same result
  • Avoid unwanted autoboxing and unboxing in the code
  • Use null safe methods and libraries
  •  Avoid returning null from a method
  • Use apache commons StringUtils for String operations
  • Avoid passing of Null Parameters

Q38. What are the common data structures and algorithms used in Java?

Ans. The following most common data structures and algorithms used in Java:

Linear Data Structures

  • Arrays
  • Linked List
  • Stacks
  •  Queues

Hierarchical Data Structures

  • Binary Trees
  • Heaps
  • Hash Tables

Also Read>> Kotlin vs Java: Why Should You Choose Kotlin Over Java

Q39. Explain the Collection Framework in Java.

Ans. The Java Collection framework provides an architecture to store and manage a group of objects. It defines several algorithms that can be applied to collections and maps. It enables the developers to access prepackaged data structures as well as algorithms to manipulate data.

The Java Collection Framework includes:

  • Interfaces
  • Classes
  • Algorithm

Q40. What are the benefits of the Java Collection Framework?

Ans. The following are the benefits of the Java Collection Framework:

  • Provides useful data structures and algorithms to reduce programming effort
  • Increases the speed and quality of the program
  • Promotes interoperability among unrelated APIs
  • Reduces the effort required to learn, use, and design new APIs
  • Encourages reusability of software

Q41. How will you convert an ArrayList to Array and an Array to ArrayList?

Ans. We can convert an Array into an ArrayList by using the asList() method.  



An ArrayList can be converted into Array using the toArray() method.


List_object.toArray(new String[List_object.size()])

Q41. What is a Linked List? What are its different types?

Ans. A linked list is a linear data structure in which each element is considered as a separate object or entity in itself. Every element within a list consists of the data and the reference to the next node.

The different types of Linked Lists are:

  • Singly Linked List: Each node stores two information – the address of the next node and the data.
  • Doubly Linked List: Each node has two references – reference to the next node and the previous node.
  •  Circular Linked List: All nodes are connected to each other. It can be singly circular or doubly circular.

Q42. What is the emptySet() method in the Java Collections framework?

Ans. The Collections.emptySet() returns the empty (immutable) Set whenever the programmer attempts to remove null elements.  It returns a serializable Set. The syntax of emptySet() is as follows:


public static final <T> Set<T> emptySet()


In case you have recently completed a professional course/certification, then

Click here to submit your review and get FREE certification highlighter worth Rs. 500.

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