Tuesday, September 12, 2023

21 Frequently Asked Java Interview Questions Answers for 2 to 3 Years Experienced

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 many 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 a 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 a task for you to collect as many as possible and keep them handy to avoid searching from them just before the interview. I will also add some more questions to 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 a 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 this kind of fact-based question on their Java recruitment drives. 

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


1. How does Java achieve platform independence? (answer) 
Answer: When we say Java is platform-independent which means Java programs are not dependent on any platform, architecture, or operating systems like Windows or Linux. Java achieves this by using Java virtual machine, when Java programs are compiled they are converted to a .class file which is a 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. 



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

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

to learn more about classloaders in Java, see my article on 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?  (solution)
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 frequently asked questions 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 the List interface while HashSet implements the Set interface in Java.
  2. ArrayList is an ordered collection and maintains the 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 a HashMap instance.
  5. One more difference between HashSet and ArrayList is that it's index-based you can retrieve objects by calling get(index) or remove objects by calling remove(index) while HashSet is completely object based. HashSet also doesn't provide the 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 best Java Collections and Streams Courses to start with. 




5. What is double-checked locking in Singleton?  (detailed answer)
Answer: The interviewer will never stop asking this question. It's the mother of all frequently asked questions in Java. Singleton means we can create only one instance of that class, in terms of singleton DCL is the way to ensure that at any cost only one instance is created in a multi-threaded environment its possible that simultaneously two threads trying to create an 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 are 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 to the previous Java questions. There are more than one ways to do it. You can create a 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 the instance will not be visible until it's 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 variables in Java? 
Answer: Volatile keyword is used with an only variable in Java and it guarantees that the value of the 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 it's guaranteed that all reader threads will see the updated value of the volatile variable once the write operation is completed, without volatile keywords different reader threads may see different values. 

The volatile modifier also helps to prevent reordering of code by the compiler and offers 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 the 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 variables in Java, see this tutorial.


9. Difference between transient and volatile variables in Java? 
Answer: This is again a follow-up of the previous two Java questions. You will see this question in the top 10 on any list of Java frequently asked questions. 

Here are some of the important differences between them.

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

Volatile variable: volatile keyword is used with an only variable in Java and it guarantees that the value of the volatile variable will always be read from the 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)
Answer: If I say this is one of the most frequently asked Java questions on both face-to-face and telephonic interviews 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 a Serializable interface which is a marker interface (an interface without any method). While Externalizable is used to customize and control the default serialization process which is implemented by the application. 

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

The externalizable interface has two methods writeExternal(ObjectOutput) and readExternal(ObjectInput) method which are used to handle customized object serialize processes and in terms of performance it's 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)
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 then they are bonded with a class at compile time not in run time so we cant reference those methods 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. The main differences 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 the case of single-threaded applications.
  • Hashtable is a legacy class, which was previously implemented Dictionary interface. It was later retrofitted into the Collection framework by implementing the Map interface. On the other hand, HashMap was part of the framework from its inception.
  • You can also make your HashMap thread-safe by using Collections.synchronizedMap() method. Its 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)
Answer: One more classic frequently asked question. List and set both are very useful interfaces of collections in Java and the difference between these two is list allows duplicate element but the set don't allow duplicate elements another difference is list maintain the insertion order of the 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 sometimes also asked as the difference between Map, List, and Set to make it more comprehensive as those three are major data structures from Java's Collection framework. To answer that question see this article.


14. Difference between ArrayList and Vector in Java?  (answer)
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 go to see this question at some point in time. Vector and ArrayList both implement the list interface but the main difference between these two is a vector is synchronized and thread-safe but the list is not because this list is faster than a vector.


15. Difference between Hashtable and ConcurrentHashMap in Java? (answer)
Answer: Both Hashtable and ConcurrentHashMap are used in the multi-threaded environment because both are thread-safe but the main difference is on performance Hashtable's performance become poor if the size of Hashtable becomes large because it will be locked for a 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 its thread-safety, scalability using lock stripping and nonblocking algorithm, see this article as well.


16. Which two methods you will override for an Object to be used as a Key in HashMap?
Answer: equals() and hashCode() methods need to be overridden for an object to be used as a key in HapMap. 

In Map, objects are stored as keys 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 a key object, and both key and value objects are stored as map.entry.

If two key objects have the same hash-code then only the value object is stored in that same bucket location but as a linked list value is stored and if the hash code is different then another bucket location is created. 

While retrieving get(key) method is used at this time hash code of the key object is calculated and then the equals() method is called to compare the value object. to learn more about how the get() method of HashMap or Hashtable works, see that article.


17. Difference between wait and sleep in Java? (detailed answer)
Answer:  Here are some important differences between wait and sleep in Java
  1. wait() method releases the lock when the thread is waiting but the sleep() method holds the lock when the thread is waiting.
  2. wait() is an instance method and sleep is a static method.
  3. The wait method is always called from a 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 awakened by calling notify method.
  5. The wait method is condition-based while the sleep() method doesn't require any condition. It is just used to put the 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)
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 an equal chance to compete for CPU, use the notifyAll method. See here more differences between notify vs notifyAll.


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


20. Difference between PATH and Classpath in Java?  (Answer)
Answer: PATH is an environment variable in Java that is used to help Java programs to compile and run. To set the PATH variable we have to include the JDK_HOME/bin directory in the PATH environment variable and also we cannot override this variable. 

On the other hand, the 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 directories 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 extending Thread and implementing Runnable in Java?  (answer)
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 extend the Thread class in Java. If you like to dig more, see this answer.


That's all on this list of 21 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 the 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 interviews, 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

15 comments:

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

    ReplyDelete
    Replies
    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

      etc.

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

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

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

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

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

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

    ReplyDelete
  7. What is difference between class and function?

    ReplyDelete
    Replies
    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.

      Delete
  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

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

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

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

    ReplyDelete

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