Core Java Interview Questions Core Java Interview Questions

Page content

Comprehensive List of Java Interview Questions based on my personal interview experience over the last few years. Sequence of Questions in each section are in the order of recent interview trends. Keep following this post link for regular updates.

Also Read Java 8 Interview Questions
Also Read Java Multithreading (Concurrency) Interview Questions

1. Java Design Patterns

Q1. What is Singleton Pattern and how do you implement it?

This is one of the most commonly asked question in interviews. Interviewer starts this question asking about design patterns. Candidate generally answers singleton and factory patterns. Then interviewer asks to write a singleton class. You should learn how to create a singleton class with private constructor, static getInstance method, double checked locking. You should also learn enum based singleton class. Follow up questions in singleton pattern are as follows:

  • How to make singleton class thread safe?
  • How to prevent deserialization to create new object of singleton class?
  • How to prevent cloning and reflection to create new object of singleton class?

Read Singleton Design Pattern Using Java for singleton class implementation and answers of above questions.

Q2. What is Immutable Object? How do you write an Immutable Class?

If you know the internal implementation of String class and know how String is immutable, you can answer it easily. Here are few points to remember:-

  • Declare the class as final so it can’t be extended.
  • Initialize all the fields via a constructor. Make all fields private so that direct access is not allowed. Make all fields final so that they’re initialized only once inside the constructor and never modified afterward.
  • Don’t provide setter methods.
  • When exposing methods which return mutable object then you must always return a new object with copied content of mutable object whereas, Immutable variables can be returned safely without extra effort.

Read Immutable Class in Java for Immutable Class implementation and answers of above questions.

Q3. Give example of 5-6 design patterns being used in Java classes.

  • Factory
  • Abstract Factory
  • Builder
  • Decorator
    All subclasses of, OutputStream, Reader and Writer.
  • Chain of responsibility
  • Iterator
  • Observer
    JMS message listener
  • Singleton
  • Adapter
    java.util.Arrays#asList() (returns a Reader) (returns a Writer)
  • Immutable
    String, Integer, Byte, Long, Float, Double, Character, Boolean and Short

2. Java Collections

Q1. How HashMap Works?

This is also most commonly asked question in collections. Interviewer start this question asking about collections and what are the data structure/collection you have used in development. Candidate generally answers HashMap, LinkedList, ArrayList, HashSet. Then interviewer check your knowledge of equals, hashcode and hashing algorithm. You should be aware of HashMap class internal implementation. Follow up questions in HashMap are as follows:

  • How to use HashMap in multi threading environment?
    You should know that HashTable is thread safe. You can make HashMap thread safe by using Collections.synchronizedMap(Map)
  • What is Concurrent HashMap? How it is better then thread safe HashMap in multi threading environment?
    Synchronized HashMap locks the whole map when one thread is accessing it resulting into other thread to wait. Concurrent HashMap provides the better performance by locking only the specific segment (similar to bucket in hashmap) rather than blocking whole map. By default, there are 16 segments, means 16 locks, means 16 concurrency level, means 16 threads can access 16 different segment of the map at the same time.

Q2. What is the difference in ArrayList and LinkedList?

ArrayList vs LinkedList
1.ArrayList implements List and RandomAccess interfacesLinkedList implements List and Deque interface
2.ArrayList internally uses a dynamic array to store the elements.LinkedList internally uses a doubly linked list to store the elements.
3.ArrayList elements are stored in contiguous memory location where each memory location represents an indexEach LinkedList element can be stored at different memory location where each element has address of it previous and next element.
4.Insertion and Deletion of elements is slow in ArrayList as these operations require all the elements to shift by one index to either make the space or fill the empty spaceInsertion and Deletion of elements is faster in LinkedList as these operations just require to change the addresses in previous and next block
5.Read operation of random element is much faster in ArrayList due to indices and support of fast random accessRead operation of random element in slower in LinkedList as need to traverse the list of find element
6.Recommended when read operation is more than the number of insertions and deletionsRecommended when insertion and deletion rate is higher then the read operation
get(int index)O(1)O(n) with n/4 steps on average
getFirst(), getLast()NAO(1)
add(int index, E element)O(n) with n/2 steps on averageO(n) with n/4 steps on average
addFirst(), addLast()NAO(1)
remove(int index)O(n) with n/2 steps on averageO(n) with n/4 steps on average
removeFirst(), removeLast()NAO(1)
Iterator.remove()O(n) with n/2 steps on averageO(1)
ListIterator.add(E element)O(n) with n/2 steps on averageO(1)
  • ArrayList: Many of the operations need n/2 steps on average, constant number of steps in the best case (end of list), n steps in the worst case (start of list)
  • LinkedList: Many of the operations need n/4 steps on average, constant number of steps in the best case (e.g. index = 0), and n/2 steps in worst case (middle of list)

Q3. How to find middle element of Linked List?

  • It is always better to keep track of Linked list size by increasing or decreasing the counter by 1, on addition or deletion of nodes from linked list respectively. In this way, middle element’s index will be (size -1)/2
  • When size of the linked list is unknown and only head node is given then you should use Fast and Slow pointer approach.
    In this approach, we iterate through the linked list using two pointers. Fast pointer jumps 2 nodes in each iteration, and the slow pointer jumps only one node per iteration.
    When the fast pointer reaches the end of the list, the slow pointer will be at the middle element.

Also read How to find middle element of LinkedList in Java for more details

Q4. How to find a loop in LinkedList?

If you answer it then follow up question might be asked:

  • How to find the starting point of loop in LinkedList?
  • How to find the length of the loop in LinkedList?

Q5. Difference between ArrayList and Vector.

These is legacy interview questions which is not asked frequently now a days but good to know.

ArrayList vs Vector
1.ArrayList’s methods are not synchronizedVector’s methods are synchronized
2.ArrayList is fast as it’s non-synchronized.Vector is slow because it is synchronized
3.If internal array runs out of room, ArrayList increases its size by 50%Vector defaults to doubling size of its array
4.ArrayList can only use Iterator for traversingVector can use both Enumeration and Iterator for traversing over elements

3. Java String

Q1. What is String Constant Pool?

String Constant Pool is a pool of Strings (String literals) stored in Java Heap Memory. A dedicated space is provided for pool in Heap Memory.

When you ask for a string from this pool, it provides the same string if already exist, otherwise it creates a new string in the pool and returns that string. This process is also called as string intern which makes the string literals reusable.

Q2. Difference between String Literal and New String Object.

String literal vs New String Object
String LiteralsNew String Object
String literals are maintained in String Constant PoolNew String objects are created in Heap Memory
String literals are interned by defaultNew String objects can be interned explicitly using intern() method
  // String Literal
  String a = "abc"; 
  String b = "abc";
  System.out.println(a == b);  // true

  // String Object
  String c = new String("abc");
  String d = new String("abc");
  System.out.println(c == d);  // false
  System.out.println(c.intern() == d.intern());  //true

Q3. Difference between String, StringBuilder and StringBuffer.

String vs StringBuilder vs StringBuffer
  • String object is immutable whereas StringBuffer and StringBuilder objects are mutable.
  • String’s concat “+” operator internally uses StringBuffer or StringBuilder class.
StringBuilder vs StringBuffer
  • StringBuilder and StringBuffer provides similar methods such as substring(), insert(), append(), delete()
  • StringBuffer is thread safe and synchronized whereas StringBuilder is not, thats why StringBuilder is more faster than StringBuffer.
  • Most of the time you will be using StringBuilder. Use StringBuffer if you really are trying to share a buffer between threads.

Q4. Why char[] array is used over String to store password in Java?

Strings are immutable in Java and any change in a String object produces a new String. When you store passwords in a String object, they stays in memory until Garbage collector clear it, which is a security threat as anyone with access to the memory dump retrieve the password from memory.

Moreover, String use String Pool memory for reusability, which even stays in memory for long duration as compare to other objects.

Whereas if password is stored in char[] array, we can explicitly wipe the password after completing the work. The array can be overwritten and password will no longer be there in memory.

5. Java Basic

Java Core interview questions are very important for freshers.

Q1. Explain each keyword in main method i.e. public static void main(String[] args).

public class MyClass {
  public static void main(String[] args) {}
  • public method have public access and can be executed from outside the class. It has to be public so that java runtime can execute this method.
  • static associates the method with class rather than object. This helps JVM to call main method without class instantiation.
  • void is a return type of main method which returns nothing
  • main is name of java main method and it is fixed. When you execute a class fine, it looks for main method.
  • String[] args It stores Java command line arguments and is an array of type String

Q2. What is final keyword in Java?

The final keyword is used as non-access modifier in Java. A final keyword can be used in different contexts such as:

  • Value of final variable cannot be changed once assigned.
  • A final method cannot be overridden by inheriting child classes in Java.
  • A final class cannot be extended by other classes in Java.

Q3. Can you override a static method and private method ?

  • No, you cannot override static method since static method is associated with a class whereas overriding is an object instance feature.
  • No, you cannot override private method since private method is not visible outside of a class.

Q4. Explain JDK, JRE and JVM

It stands for Java Development KitIt stands for Java Runtime EnvironmentIt stands for Java Virtual Machine
It contains JRE, JVM, interpreter/loader(java), compiler(javac), debugger, archiver(jar), document generator(JavaDoc)It contains JVM, Class libraries and other supporting filesIt is a virtual machine contains ClassLoader, Method Area, Heap, Stack memory
You can compile, document, debug, or archive a Java Program with JDKYou can execute a Java Program with only JRE, You don’t need JDKJVM translates the bytecode to native machine code

Q5. Why Java is platform independent?

Java is platform independent. Let’s understand this

  • When you write a program in Java (.java file) and compile it using javac. It is converted to ByteCode (.class file).
  • This ByteCode is not something which any machine or OS can understand. You need an interpreter to execute this ByteCode and that interpreter is JVM (Java Virtual Machine) in case of Java.
  • JVM is platform dependent. You need to install platform specific JVM based on Operating System you are using Mac OS X, Windows or Linux.
  • You can execute the same ByteCode (.class file) on any platform’s JVM regardless of its Operating System.

So we can say, JVM is platform dependent but Java is platform independent from its magic ByteCode.

Q6. How many ways to create an Object Instance in Java ?

  • New Keyword
  • Cloning using Object.clone() method
  • Reflection using Class.newInstance() method
  • Reflection using Class.getConstructor().newInstance() method
  • Object Serialization and Deserialization
public class ObjectInstance {

	public static void main(String[] args)
			throws CloneNotSupportedException, InstantiationException, IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, NoSuchMethodException, SecurityException, IOException, ClassNotFoundException {
        // New Keyword
		ObjectInstance instance1 = new ObjectInstance();

		// Cloning
		ObjectInstance instance2 = (ObjectInstance) instance1.clone();

		// Reflection
		ObjectInstance instance3 = ObjectInstance.class.newInstance();
		ObjectInstance instance4 = ObjectInstance.class.getConstructor().newInstance();

		// Object Serialization and Deserialization
		ObjectInstance instance5 = deserialize();


	private static void serialize(ObjectInstance objInstance) throws IOException {
		FileOutputStream f = new FileOutputStream("resources/objectinstance.ser");
		try (ObjectOutputStream outputStream = new ObjectOutputStream(f)) {

	private static ObjectInstance deserialize() throws IOException, ClassNotFoundException {
		FileInputStream f = new FileInputStream("resources/objectinstance.ser");
		try (ObjectInputStream inputStream = new ObjectInputStream(f)) {
			return (ObjectInstance) inputStream.readObject();

Q7. What is Marker Interface?

A Marker interface is an empty interface (having no fields and methods). Examples of Marker interface are:-,
java.util.RandomAccess etc.

Marker Interface provides runtime information about objects to compiler and JVM. Now annotations are used for the same purpose instead of Marker Interface.

Let’s create our own marker interface Deletable to indicate whether an object can be removed from the database.

public interface Deletable {}

public class Entity implements Deletable {
    // implementation details

public class ShapeDao {
    // other dao methods
    public boolean delete(Object object) {
        if (!(object instanceof Deletable)) {
            return false;
        // delete implementation details
        return true;

6. Java Advance

Q1. What is the difference between Heap and Stack Memory in Java?

MemoryStack memory is used only by one thread of execution.Heap memory is used by all the parts of the application.
AccessStack memory can’t be accessed by other threads.Objects stored in the heap are globally accessible.
Memory ManagementFollows LIFO manner to free memory.Memory management is based on the generation associated with each object.
LifetimeExists until the end of execution of the thread.Heap memory lives from the start till the end of application execution.
UsageStack memory only contains local primitive and reference variables to objects in heap space.Whenever an object is created, it’s always stored in the Heap space.

Q2. Explain Java Memory Model with Heap structure. Explain here three parts of heap i.e. Young, Old and Permanent Generation. Also Explain Minor and Major GC

Q3. How to do JVM performance tuning ? Explain here parameters

a) Heap Memory: -Xms, -Xmx, -Xmn,
b) Permanent Generation Memory: -XX:PermSize, -XX:MaxPermSize
c) Garbage Collection i.e. 
    -XX:+UseParellelGC (-XX:ParellelGCThreads=<N>), 
    -XX:+UseConcMarkSweepGC (-XX:ParellelCMSThreads=<N>), 

Q4. What is classloader in java? How to write custom class Loader? What is linkage error?

Q5. Do you know about serialization? When should we use that? What is the role of Serialization id? serializable vs externalizable?

Q6. Deep vs Shallow copy in Cloning?

7. Java Theory

Q1. S.O.L.I.D. (5 class design principle) in Java ?

These 5 design principle are know as SOLID principles:-

  • Single Responsibility Principle - One class should have one and only one responsibility
  • Open Close Principle - Software components should be open for extension, but closed for modification
  • Liskov Substitution - Derived types must be completely substitutable for their base types
  • Interface Segregation - Clients should not be forced to implement unnecessary methods which they will not use
  • Dependency Inversion - Depend on abstractions, not on concretions

Q2. Anti patterns in Java. What is god class ?

Anti patterns in java is:-

  • Any pattern or coding habit which is considered as bad practice
  • Which are against SOLID design principles

God class is one of the Anti pattern example. A god class is a class which is having too many properties or methods or dependencies and hence lots of responsibilities which violates single-responsibility SOLID design principle. Writing thousands lines of code in single class becomes a nightmare to debug, unit-test and document.

  • Association (bidirectional one to one, one to many, many to one or many to many association, represented by line with arrow in UML) for e.g. Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle.
  • Aggregation (Has-a relationship, unidirectional association, parent and child can survive individually, represented by line with diamond in UML) for e.g. Car and Wheel. Car can have multiple wheels but wheel can not belong to multiple cars and if we delete the car, wheel need not to be destroyed and used in another car.
  • Composition (Part-of relationship, unidirectional association, child can not survive without parent, represented by line with filled diamond in UML) for e.g. House and Rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete.

Q4. 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 the 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 to as Diamond Problem.