Tuesday, January 26, 2021

Top 21 Frequently Asked Java Interview Questions Answers

If you have been to a couple of Java interviews then you know that there are some questions that keep repeating like the difference between == and equals() method and may of its popular cousins like HashMap vs Hashtable, ArrayList vs LinkedList, the difference between equals() and hashCode(), or difference between Comparator and Comparable in Java. I call them frequently asked Java interview questions, and I suggest every Java developer make a list of them for their own reference and revision. I am sure many Java programmer already has such list of questions handy if you don't have then this is a good time to find and make your own list, or if you are in rush then you can also buy my book Grokking the Java Interview, which contains many such questions. 

These are the questions which you simply can't afford to miss, especially at freshers level. They appear at various stages of Java interviews. Most likely you will see them on a telephonic round, where the Interviewer just wants to filter candidates between who knows Java and who doesn't.

The good thing about them is that they are so common that everyone knows about them. Though for freshers it could be a little difficult, as your experience grows these frequently asked questions become much easier to answer.

Some programmers also prefer to collect frequently asked Java questions based upon topics like common questions from threads, strings, collections, and other popular Java interview topics, some of them are already shared by me. In this list, I am sharing some of the most frequently asked questions from Java interviews.

By the way, when you look at the list, you will see some of the classics are missing like the difference between String and StringBuffer, but there are many like that, and that is task for you to collect as many as possible and keep them handy to avoid searching from them just before interview. I will also add some more questions on this list but for now let's start with these 21 questions.

21 Frequently Asked Core Java Question and Answer

Here is my list of some of the most common questions from Java interviews. You will mostly see these questions on telephonic round of your interview, but it is also asked a lot of time during face to face interviews. 

It's not limited to any particular company as well, in fact all major IT companies in India like TCS, CTS, Infosys, Tech Mahindra, HCL, Oracle Financial Services, and major investment banks like Barclays Capital, Morgan Stanley, Goldman Sachs, Credit Suisse asked these kind of fact based question on their Java recruitment drives. 

By the way, some questions are really easy, and some are real tough, so it's mixed of both, but one thing is common, they are the most frequently asked questions from Java interviews.

1)  How Java achieves platform independence? (answer)

Answer : When we say Java is platform-independent which means Java programs are not dependent on any platform, architecture or operating system like windows or Linux. Java achieve this by using Java virtual machine, when Java programs are compiled they are converted to .class file which is collection of byte code and directly understandable by JVM. 

So the same Java program can run on any operating system only JVM can differ according to OS but all JVM can understand converted byte code that's how Java achieve platform independence. You can further see a comprehensive Java course like The Complete Java Masterclass to learn more about Java architecture and the essentials of the Java Programming language. 

Frequently Asked Java Interview Questions Answers

2)  What is ClassLoader in Java?

Answer : This was one of advanced question few years ago, but in span of two to three years, this has become very common. When a Java program is converted into .class file by Java compiler  which is collection of byte code  class loader is responsible to load that class file from file system,network or any other location. 

This class loader is nothing but also a class from which location they are loading the class according to that class loaders are three types :
  3.System class loader .

to learn more classloaders in Java, see my article how classloader works in Java.

frequently asked java questions from interviews

3)  Write a Java program to check if a number is Even or Odd?

Answer : This question is not particularly related to Java and also asked on other programming interviews like C, C++ or C#. I have included this in my list of frequently asked questions from Java interviews because I have seen it more often than not.

import java.util.Scanner;

class TestEvenOdd {
 public static void main(String arg[]){
   int num;
   //Read a number
   Scanner input = new Scanner(System.in);
   System.out.println("Enter a number to check its Even or Odd");
   num = input.nextInt();
   // Conditional operator
   System.out.println((num%2)==0 ? "even number":"odd number");
This is the easiest coding problem you can get on Java interviews but nowadays it's getting tougher and tougher and you may be asked to solve dynamic programming-based problems. At a bare minimum I suggest you get yourself familiar with essential coding patterns like sliding window, merge interval, two pointers approach, and top k elements, this will help you a lot in solving coding problems on Java interviews. 

If you need a resource, I highly recommend Grokking the Coding Interview: Patterns for Coding Questions course on Educative. It's an interactive course to learn 15 essential coding patterns for interviews. You can buy this course or get an Educative subscription for $14.99 per month to get access to all of their best courses for coding interviews. 

frequently asked coding question form java interviews

4)  Difference between ArrayList and HashSet in Java?

Answer : If I say that this is one of the most most frequently asked question to Java programmers, then it would not be wrong. Along with questions like ArrayList vs LinkedList and ArrayList vs Vector, this question is most common in various Java interviews. Here are some important differences between these two classes :
  1. ArrayList implements List interface while HashSet implements Set interface in Java.
  2. ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn't maintain any order.
  3. ArrayList allow duplicates while HashSet doesn't allow duplicates.
  4. ArrayList is backed by an Array while HashSet is backed by an HashMap instance.
  5. One more difference between HashSet and ArrayList is that its index based you can retrieve object by calling get(index) or remove objects by calling remove(index) while HashSet is completely object based. HashSet also doesn't provide get() method.
On the same note, collections are very important topics for Java interviews, I highly recommend you to prepare this topic well, If you need resources, you can check out these Java Collections and Streams Courses to start with. 

5)  What is double checked locking in Singleton?

Answer : Interviewer will never stop asking this question. It's mother of all frequently asked question in Java. Singleton means we can create only one instance of that class,in term of singleton DCL is the way to ensure that at any cost only  one instance is created in multi-threaded environment its possible that simultaneously two thread trying to create instance of singleton class in that situation we cant sure that only one instance is created so avoid this situation using double checked locking by using synchronized block where we creating the object.

Code Example :
class SingletonClass {
  private DCL dcl = null;
  public DCL getDCL() {
    if (dcl == null) {
      synchronized {
        if (dcl == null)
          dcl = new DCL();
    return dcl;
To learn more about why double-checked locking was broken before Java 1.5, see this article.

6)  How do you create thread-safe Singleton in Java?

Answer: This is usually a follow-up of the previous Java questions. There are more than one ways to do it. You can  create thread safe Singleton class in Java by creating the one and only instance during class loading. static fields are initialized during class loading and Classloader will guarantee that instance will not be visible until its fully created. You can further see my article for a code example to create a thread-safe singleton in Java. 

7)  When to use volatile variable in Java?

Answer : Volatile keyword is used with only variable  in Java and it guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache. So we can use volatile to achieve synchronization because its guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values. The volatile modifier also helps to prevent reordering of code by compiler and offer visibility guarantee by happens-before relationship. See this article to learn more about volatile in Java.

8)  When to use a transient variable in Java?

Answer: Transient in Java is used to indicate that the variable should not be serialized. Serialization is a process of saving an object's state in Java. When we want to persist and the object's state by default all instance variables in the object are stored. In some cases, if you want to avoid persisting some variables because we don’t have the necessity to transfer across the network. 

So, declare those variables as transient. If the variable is declared as transient, then it will not be persisted. This is the main purpose of the transient keyword, to learn more about transient variable in Java, see this tutorial.

9)  Difference between transient and volatile variable in Java?

Answer : This is again follow-up of previous two Java questions. You will see this question on top 10 on any list of Java frequently asked question. 

Here are some of the important difference between them.

Transient variable : transient keyword is used with those instance variable which will not participate in serialization process.we cannot use static with transient variable as they are part of instance variable.

Volatile variable : volatile keyword is used with only variable  in Java and it guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache, it can be static.
to learn more differences and answer this question in detail, see here.

10) Difference between Serializable and Externalizable in Java?

Answer: If I say this is one of the most frequently asked Java questions on both face-to-face and telephonic interview then it would be an exaggeration. Serialization is a default process of  serializing or persisting  any object's state in Java. 

It's triggered by implementing Serializable interface which is a marker interface (an interface without any method). While Externalizable is used to customize and control default serialization process which is implemented by application. 

Main difference between these two is that Externalizable interface provides complete control to the class implementing the interface whereas Serializable interface normally uses default implementation to handle the object serialization process.

Externalizable interface has two method writeExternal(ObjectOutput) and readExternal(ObjectInput) method which are used to handle customized object serialize process and in terms of performance its good because everything is under control. to learn more about this classical question, see this answer as well.

11) Can we override the private method in Java?

Answer : No, we cannot override private methods in Java as if we declare any variable ,method as private that variable or method will be visible for that class only, and also if we declare any method as private than they are bonded with class at compile time not in run time so we cant reference those method using any object so we cannot override private method in Java.

12) Difference between Hashtable and HashMap in Java?

Answer: This is another frequently asked question from the Java interview. Main difference between HaspMap and Hashtable are the following :
  • HashMap allows null values as key and value whereas Hashtable doesn't allow nulls.
  • Hashtable is thread-safe and can be shared between multiple threads whereas HashMap cannot be shared between multiple threads without proper synchronization.
  • Because of synchronization, Hashtable is considerably slower than HashMap, even in case of single threaded application.
  • Hashtable is a legacy class, which was previously implemented Dictionary interface. It was later retrofitted into Collection framework by implementing Map interface. On the other hand, HashMap was part of framework from it's inception.
  • You can also make your HashMap thread-safe by using Collections.synchronizedMap() method. It's performance is similar to Hashtable.
See here to learn more and understand when to use Hashtable and HashMap in Java

13) Difference between List and Set in Java?

Answer: One more classic frequently asked question. List and set both are very useful interfaces of  collections in Java and  difference between these two is list allows duplicate element but set don't allows duplicate elements another difference is list maintain the insertion order of element but the Set is an unordered collection. 

The List interface can have many null objects but the set permits only one null element. This question is some time also asked as difference between Map, List and Set to make it more comprehensive as those three are major data structure from Java's Collection framework. To answer that question see this article.

14) Difference between ArrayList and Vector in Java?

Answer: One more favorite of Java Interviewers, there is hardly any interview of junior Java developers, on which this question doesn't appear. In four and five rounds of interviews, you will definitely going to see this question in some point of time. Vector and ArrayList both implement the list interface but main difference between these two is vector is synchronized and thread safe but list is not because of this list is faster than vector.

15) Difference between Hashtable and ConcurrentHashMap in Java?

Answer : Both Hashtable and ConcurrentHashMap is used in multi-threaded environment because both are therad-safe but main difference is on performance Hashtable's performance become poor if the size of Hashtable become large because it will be locked for long time during iteration but in case of concurrent HaspMap  only specific part is locked because concurrent HaspMap works on segmentation and other thread can access the element without iteration to complete. To learn more about how ConcurrentHashMap achieves it's thread-safety, scalability using lock stripping and non blocking algorithm, see this article as well.

16) Which two methods you will override for an Object to be used as Key in HashMap?

Answer: equals() and hashCode() methods needs to be override for an object to be used as key in HaspMap. In Map objects are stored as key and values.  put(key ,value) method is used to store objects in HashMap at this time hashCode() method is used to calculate the hash-code of key object and both key and value object is stored as map.entry.if two key objects have same hash-code then only value object is stored in that same bucket location but as a linked list value is stored and if hash code is different then another bucket location is created. While retrieving get(key) method is used at this time hash code of key object is calculated and then equals() method is called to compare value object. to learn more about how get() method of HashMap or Hashtable works, see that article.

17) Difference between wait and sleep in Java?

Answer:  Here are some important differences between wait and sleep in Java
  1. wait() method release the lock when thread is waiting but sleep() method hold the lock when thread is waiting.
  2. wait() is a instance method and sleep is a static method .
  3. wait method is always called from synchronized block or method but for sleep there is no such requirement.
  4. waiting thread can be awake by calling notify() and notifyAll() while sleeping thread can not be awaken by calling notify method.
  5. wait method is condition based while sleep() method doesn't require any condition. It is just used to put current thread on sleep.
  6. wait() is defined in java.lang.Object class while sleep() is defined in java.lang.Thread class

18) Difference between notify and notifyAll in Java?

Answer: the main difference between notify and notifyAll is notify method will wake up  or notify only one thread and notifyall will notify all threads. If you are sure that more than one thread is waiting on the monitor and you want all of them to give equal chance to compete for CPU, use notifyAll method. See here more differences between notify vs notifyAll.

19) What is the load factor of HashMap means?

Answer: HashMap's performance depends on two things first initial capacity and second load factor whenever we create HashMap initial capacity number of bucket is created initially and load factor is criteria to decide when we have to increase the size of HashMap when its about to get full.

20) Difference between PATH and Classpath in Java?

Answer: PATH is an environment variable in Java which is used to help Java program to compile and run.To set the PATH variable we have to include the JDK_HOME/bin directory in PATH environment variable and also we cannot override this variable. On the other hand,  ClassPath variable is used by the class loader to locate and load compiled Java codes stored in .class file. We can set classpath we need to include all those directory where we have put either our .class file or JAR file which is required by your Java application,also we can override this environment variable.

21) Difference between extends Thread and implements Runnable in Java?

This is the 21st frequently asked question on my list. You will see this question as first or second on a multi-threading topic. One of the main points to put across while answering this question is Java's multiple inheritance support. You cannot more than one class, but you can implement more than one interface.  

If you extend the Thread class just to override the run() method, you lose the power of extending another class, while in the case of Runnable, you can still implement another interface or another class. One more difference is that Thread is an abstraction of an independent path of execution, while Runnable is an abstraction of the independent task, which can be executed by any thread. 

That's why it's better to implement Runnable than extending the Thread class in Java. If you like to dig more, see this answer.

That's all on this list of 20 most frequently asked Java interview questions and answers. By the way, this is not just the only list you got here, I have shared a lot of interview questions on topic wise like you can find frequently asked questions from Thread, Collections, Strings and other important Java classes. 

Apart from coding questions, these fact-based Java programming language questions are very important to do well in an interview. It's even more important for freshers and less experienced developers because they are usually asked these questions more frequently than experienced developers. By the way, you are most welcome to contribute to this list.

Related Interview Questions from Java67 blog

Thanks for reading this article so far. If you like these Java  interviews questions or have seen them on your telephonic round of interview, then please share this post with your friends and colleagues on Facebook, Twitter, Email, etc. If you have any questions or feedback, please drop a note.

All the best Guys


  1. Can you please share a list of frequently asked Java programs on Interviews as well?

    1. Interesting question, some of the frquently asked programs on Java interviews are :
      - reverse string without using stringbuffer
      - writing code to avoid deadlock
      - four ways to loop over map
      - multi-threaded version of getInstance() method of Singleton class
      - count number of 1 in an integer number
      - converting string to bytes


  2. Great article. In #5, the Singleton example - you may want to show the private constructor method for the SingletonClass. As written, you could create multiple instances of the SingletonClass, each with their own DCL object.

    1. Another way which a thread safe Singleton can be created is using Enum.

  3. Couple of core Java questions which have seen more frequently on interviews are :

    - can two unequal object has same hashcode?
    - can we create instance of abstrat class?
    - how do you make an object immutable?
    - difference on comparing String over == and equals?
    - difference between comparator and comparable?

    I like to contribute because I have benefitted a lot from your side :) Thank you very much for your time and effort.

  4. I love Java interviews, most of the time you will see these repeated, frequently asked question, which even a kid can answer. If you are an experienced Java developer, having worked for more than 4 years in industry, you don't need to worry about FREQUENTLY asked, MOST asked, TOP 20, you already know answers, better spend you time learning DataStructure, Algorithm, Programming or Design.

  5. If you are a Java Developer of just couple of month of experience but has a computer science degree, I would say to prepare well for DS and Algo, you can check some sample Data structure questions here, once you are good at that, just prepare some basic Java questions for telephonic round. Once you are done that you are ready, but if you want more confidence, you should check this Mega list of Java questions, which contains core Java questions including multi-threading, exception handling, collections, GC, design pattern and OOP questions from last 5 years of Java interviews. This will help you to clear any Java job interview, at least for small companies.

  6. Can you please share some Java interview questions from Citiback, RBS and Morgan Stanley India Mumbai for Java developers with 5+ years experience?

  7. What is difference between class and function?

    1. class is an object oriented construct which is blue print to create object, which can have both state and behavior, while function is just a block of code which is named for reuse.

  8. At 12...6+ JVMs are smart enough to detect there's no contention on certain locks and they may apply lock elision. In single threaded applications you may actually get no locking at all on a Hashtable

  9. For more interview questions based on different levels of experience, visit site http://myjavainterview.com/introduction/

  10. Now, we usually ask like these.

    What is theJMM?

    what is the Java deadlock

    Difference between ReentrantLock and synchronized?

    Do you know synchronized.cpp? What is the lock's upgrade and downgrade?

    What is the AQS?

    Do you know fork/join and copy-on-write?

    Can you explain ThreadPoolExecutor's params?

    Spring Bean lifecycle.

    Difference between CGLib and JDK Proxy.

  11. Good questions, would be glad you can provide the answers as well for people reading comments, I always do :-) Even I don't know answers of some of these questions like synchronized.cpp , never heard of it? Same with AQS, unless I am missing something.


Feel free to comment, ask questions if you have any doubt.