Skip to content

The Ultimate List of Java Interview Questions and Answers

This post on JAVA Interview Questions is intended to help you understand the fundamental concepts of Java for interview purposes.

Java Interview questions

Table of Contents

1) What is Java?

Java is a high-level, object-oriented programming language that helps developers write platform-independent code that can be executed on any platform.

2) What is the difference between JDK, JRE, and JVM?

JDK (Java Development Kit):

It is a software development kit containing tools like the compiler and debugger.JDK includes JRE, compiler, Interpreter and other tools required in Java development.

JRE (Java Runtime Environment):

It includes the JVM and essential libraries required to run Java applications.

JVM (Java Virtual Machine):

It is an execution environment that interprets Java bytecode. It is in-built into both JDK and JRE.

3) Explain access modifiers and their use in Java.

Access modifiers help in restricting the scope of the class, constructor, variable, data member, or method.

Private: Access is limited within the class.
Public: It can be accessed from anywhere like within the class, outside the class, outside the package, etc.
Protected: Access level is within the package and outside the package through child class.
Default: Access level is only within the package.

4) What is the difference between this() and super() keywords in java?

this() is used to access one constructor from another within the same class while super() is used to access the superclass constructor. Either this() or super() exists it must be the first statement in the constructor.

5) What is a constructor in Java?

We use constructors in Java to initialize all variables in the class when an object is created. Once the object is created using the ‘new’ keyword, it is initialized automatically. Its name is the same as the class name

We have three types of constructors in Java

1)Default Constructor 

This constructor is defined by default. We don’t need to explicitly define this constructor. It has no parameters.

public class Person {
    String name;
    int age;

    // Default constructor (implicit)
    public Person() {
        // No specific initialization here
    }
}


2)Parameterized Constructor.

A parameterized constructor allows you to initialize the instance variables with provided values at the time of object creation. It takes parameters as arguments and assigns them to the respective instance variables.

public class Car {
    String make;
    String model;
    int year;

    // Parameterized constructor
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }
}

3)Copy Constructor

A copy constructor creates a new object by copying the values of the instance variables from an existing object. It is helpful when you want to create a new instance with the same values as an existing one.

public class Book {
    String title;
    String author;
    int pageCount;

    // Copy constructor
    public Book(Book otherBook) {
        this.title = otherBook.title;
        this.author = otherBook.author;
        this.pageCount = otherBook.pageCount;
    }
}

6) What is constructor chaining?

Constructor chaining is the process of calling one constructor from another constructor. By using constructor chaining code optimization can be achieved. Constructor chaining is also used to access the properties of the constructor in the same class or another class.

7) What is the difference between primitive and non-primitive data types?

A primitive data type has always a value while non-primitives can be null. Primitive data types are predefined by the programming language such as int, float, char, and boolean while non-primitive created by programmers like an array, enum, etc. Primitive data types are stored in the stack while derived objects are stored in the heap and their reference in the stack.

8) What are the different ways to create objects in Java?

An object can be created in multiple ways in Java.

1)Using the New keyword

Object obj=new Object()

2)Using newInstance() Method

Class<Cat> catClass = Cat.class;
Cat cat = catClass.newInstance();

3)Using the Clone method

You can create a new object by cloning an existing object using the clone() method. For this approach to work, the class must implement the Cloneable interface.

public class Student implements Cloneable {
    String name;

    public Student(String name) {
        this.name = name;
    }

    public void display() {
        System.out.println("Name: " + name);
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

// Creating an object using object cloning
Student student1 = new Student("Alice");
try {
    Student student2 = (Student) student1.clone();
    student2.display(); // Output: Name: Alice
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
}


4)Using Deserialization

Objects can be created by deserializing data from a file or stream. The class must implement the Serializable interface for this method to work.

5)Using Class.forName() Method

An object can be created using the Class.forName() method.

9) Why String is immutable in Java?

Making a string immutable makes the string thread-safe. If the string were somehow not immutable, then changing one reference would alter the value of other references.

10) Explain what is encapsulation?

Encapsulation is the process of wrapping code and behaviour in a single unit called class and preventing misuse. Encapsulation exposes only parts of the object which are safe to expose and the remaining part of the object is kept secure.

11) What is an abstraction in Oops?

Abstraction is one of the OOPS concepts. It aims to hide the complexity from users and show them only the relevant information. Abstraction hides the underlying complexity of data by exposing only the essential features and behaviours.

In Java abstraction can be achieved either using the abstract class or using the interfaces.

12) Why do we need an interface?

Interface in Java is used to achieve code reusability and polymorphism. Interfaces are a way to declare a contract for implementing classes. The use of an interface allows us to achieve multiple inheritance and complete abstraction.

13) What is the difference between abstract class and interface?

  • An abstract class can have instance variables while an Interface can not have instance variables
  • An interface can only have abstract methods while an Abstract class can have non-abstract methods along with abstract methods.
  • An abstract class can contain constructors while Interface can not have constructors.
  • An abstract class is used to achieve partial abstraction while an interface is used to achieve full abstraction.

14) Why does an abstract class need a constructor?

The constructor is used to initialize a class’s newly created object or fields. An abstract class can have instance variables and non-abstract methods so to initialize those we may explicitly define a constructor in an abstract class. The compiler automatically adds the default constructor in every class whether it is an abstract class or a concrete class

15) Can we create the object of an abstract class?

No, We can not create the object of an abstract class.

16) Where objects are stored in Java?

Objects created are stored in heap memory and reference to those objects are stored in stack memory.

17) What is Exception handling in Java?

Exception handling is a mechanism for what to do when some abnormal situation arises in the program. When an exception is raised in the program it leads to the termination of the program when it is not handled properly. The significance of exception handling comes here in order not to terminate a program abruptly and to continue with the rest of the program normally. This can be done with the help of Exception handling.

18) List five keywords related to Exception handling.

1) Try 

2) Catch 

3) throw 

4) throws 

5) finally

19) What is the benefit of multi-catch block in Java?

By using a multi-catch block, we can handle different types of exceptions thrown from a try-block in a single multi-catch block. By doing so, the length of the program/code is decreased when compared with multiple catch blocks for each type of exception. Thus Code Conciseness and code maintainability increased.

class Test {
	public static void main (String[] args) {
        try{
            System.out.println(8/0);
        }catch(Exception e)
        {
            System.out.println("Exception : divide by 0");
        }catch(ArithmeticException e)
        {
            System.out.println("ArithmeticException :divide by 0");
        }
	}
}

20) Can we use a catch statement for checked exceptions?

If there is no chance of exception in the code then we can’t declare a catch block for handling checked exceptions. It will give a compile-time error if we try to handle checked exceptions when there is no possibility of causing exceptions.

21) Can we rethrow the same exception from the catch handler?

Yes, we can rethrow the same exception from our catch handler. If we want to rethrow a checked exception from a catch block then we need to declare that exception.

22) What is exception propagation?

When an exception is thrown from the stack and not caught, the exception again drops down to the previous method and so on until it gets caught, this is called exception propagation. Only unchecked exceptions are propagated.

23) What is the difference between a checked exception and an unchecked exception?

Exceptions that are caught at compile time are known as checked exceptions for example IOException and Interrupted Exception. Unchecked exceptions are thrown at run time for example NullPointerException, IndexOutOfBoundException, etc.

24) What is the difference between wait() and sleep() in java?

Thread. sleep is meant for introducing pause, releasing CPU, and allowing another thread to execute while wait() call on an object and releasing the lock for other objects to have a chance to execute.

25) Java is pass-by-value or pass-by-reference?

Java is officially pass by value. It means during method calls only values pass not the addresses.

26) Can we overload or override the static method?

We can overload static methods but the method signature should be different. We can’t override it because the static method only belongs to a class and not its instances so the implementation of the base class static method will be hidden by the derived class implementation.

27) Explain the difference between String, StringBuilder, and StringBuffer.

  • String: String is Immutable (cannot be changed). It’s suitable for cases where the content doesn’t change frequently.
  • StringBuilder: This is Mutable (can be changed) and Efficient for concatenating or modifying strings in place.
  • StringBuffer: Same as StringBuilder but thread-safe due to synchronized methods.

28) Explain the ‘equals’ and ‘hashCode’ methods.

‘equals’: Used to compare the references of two objects for equality. It can be overridden to provide a meaningful comparison for custom classes.

‘hashCode’: Hashcode method returns the same value if two objects are equal according to the equals() method.

29) Can we serialize static variables in Java?

We can’t serialize static variables in Java. The reason is that static variables are class variables that belong to a class, not to an object, but the serialization mechanism saves only the object state, not the class state.

30) Why do we need Enum in Java?

The main goal of the enum is to define our own/custom data types. We can add variables, methods, and constructors to it. We generally used enums in our test automation frameworks, especially when a variable can only take one out of a small set of possible values.

31) What is the difference between HashSet and TreeSet?

  • TreeSet maintains insertion order while HashSet does not maintain any order.
  • HashSet is faster than the Tree set.
  • HashSet allows null objects while tree set does not allow null objects.

32) What is the difference between HashMap and HashSet?

  • HashSet does not allow duplicate values while hashmap allows duplicate values but no null keys.
  • HashSet can have a single null value, Hashmap can have a single null key and multiple null values.

33) Differentiate between List and Set in Java.

  • The list is an ordered sequence while the Set is an unordered sequence.
  • Duplicate elements are allowed in the list but not in the set.
  • Several null elements can be stored in the list while a single null element can be stored in a set.

34) When TreeSet is preferred over HashSet?

When sorted unique elements are required because the Tree set returns a sorted list in ascending order.

35) What is the difference between a hashmap and a hashtable?

HashMap allows only one null key and can have multiple null values whereas Hashtable doesn’t allow any null key or null value.HashMap inherits the AbstractMap class while Hashtable inherits the Dictionary class.

36) What is the difference between local variables and class variables?

Local variables are those variables that are declared inside methods, constructors, and blocks which makes them thread-safe. However, class variables are declared outside methods and constructors but within the class, which is why class variables are not thread-safe.

37) What is the difference between a for-each loop and a normal for loop?

For loop is a general loop that executes repeatedly until the provided condition turns out to be false whereas the for-each loop executes until the last element gets evaluated, it does not require any termination condition like for loop. Another difference is that for-each loop does not keep track of the index and can only traverse in a forwarding direction unlike for loop.

38) What will happen if we try to insert a duplicate value in the Set?

When you try to insert a duplicate into a set, the duplicate value is ignored, and the set remains unchanged. This does not lead to any compile or runtime errors: duplicates are silently ignored.

39) How can you prevent a method from being overridden?

1)Make method static: In this way, it becomes a class method hence not allowed to be overridden.
2)Make method private: Visibility of that method reduces to class only hence can not be accessed outside the class.
3) Make method final: It Will be considered final and no other class can override the behavior.

40) How to make a class immutable in Java?

1)Declare the class as final.
2)Declare data members of the class as final and private.

41) What is the use of the Properties class in Java? What is the advantage of the Properties file?

We can configure things that are prone to change over a period of time without the need to change anything in code. A properties file is a simple collection of key-value pairs that can be parsed by Java. util. Properties class.

42) What is the difference between the isBlank() and isEmpty() method of the String class?

IsBlank() method is used to check for any non-whitespace character in the string. While isEmpty() checks whether the string is null or not. For example:

string.isBlank(” “)–Returns True.

string.isEmpty(” “)–Returns False.

43) How many ways runtime polymorphism can be achieved?

Run time polymorphism can be achieved either by interface or inheritance. Inheritance to be used in case of IS-A/An relationship e.g: Animal (parent class)->Dog, cat(subclasses).

Interface to use for Has a relationship e.g: Mobile, clock, the timer has a feature Alarm, but all these cannot be grouped into a single category. So, the Alarm will be an interface that is common to all classes.

44) Explain whether int a=null is right or wrong and Why?

Null can be used for reference type only not for primitive type. So int a=null is wrong.

45) List some common classes in Java.

A class in Java is used to create and define objects. There are so many classes in Java. A few essentials are the final, static, abstract, exception, Singelton, etc.

46) What is the difference between break and continue keywords?

Break: This keyword is used with both switch and loop statements. It is used to terminate the flow.

Continue: This keyword is used to skip the specified condition and continue the rest of the iteration, it’s used with loops only.

47) What is OutOfMemoryError?

OutOfMemory is a runtime exception in Java that occurs when JVM is unable to allocate the required memory to complete the operation. There are different types of OutOfMemory exceptions, each corresponding to a specific memory issue. Some common OutOfMemoryError types are:

  1. java. lang.OutOfMemoryError: Java heap space: This exception occurs when the JVM cannot allocate more memory for objects in the heap.
  2. java. lang.OutOfMemoryError: Metaspace: This exception occurs when the JVM cannot allocate more memory for class metadata in the metaspace (used for storing class-related information).
  3. java. lang.OutOfMemoryError: PermGen space: This exception is similar to the Metaspace error, but used in older Java versions (Java 7 and earlier) to indicate lack of space in the Permanent Generation area.
  4. java. lang.OutOfMemoryError: Requested array size exceeds VM limit: This exception occurs when trying to create an array that is larger than the JVM’s limit.

48) What is the final access modifier in Java? Explain in detail.

final access modifier can be used for class, method, and variables. The main advantage of the final access modifier is security no one can modify our classes, variables, and methods. The main disadvantage of the final access modifier is we cannot implement oops concepts in Java. 

final class: A final class cannot be extended or subclassed. We are preventing inheritance by marking a class as final. But we can still access the methods of this class by composition. Ex: String class final methods:

final method: Method overriding is one of the important features in Java. But there are situations where we may not want to use this feature. Declare the method as final.

 final variable: If a variable is declared final, it behaves like a constant. We cannot modify the value of the final variable. Any attempt to modify the final variable results in a compilation error. The error is as  follows

49) What is a ternary operator in Java?

In Java, the ternary operator is a conditional operator that takes three operands: a condition followed by a question mark (?), then an expression to be evaluated if the condition is true, followed by a colon (:), and finally an expression to be evaluated if the condition is false.

The syntax for the ternary operator is:

condition ? expression1 : expression2

50) What is the difference between == and .equals() method in Java?

  • The == operator in Java compares the memory addresses of two objects. It checks whether two object references point to the same memory location.
  • The .equals() method is used to compare the contents or values of objects.
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");

System.out.println(str1 == str2); // true, same memory location
System.out.println(str1 == str3); // false, different memory location
System.out.println(str1.equals(str2)); // true, same content
System.out.println(str1.equals(str3)); // true, same content

51) Can a constructor be private in a Java class?

Yes, we can create a private constructor in a Java class. This concept is used in singleton class where we want to restrict the creation of objects. This private constructor can only be accessed from within the class. It cannot be accessed or invoked from anywhere outside that class, including subclasses or other classes in the same package.

public class Singleton {
    // Private static instance variable
    private static Singleton instance;

    // Private constructor
    private Singleton() {
        // Initialization code if needed
    }

    // Public static method to get the singleton instance
    public static Singleton getInstance() {
        // Lazy initialization: create the instance if it's null
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    }

52) Have you worked with Predicate in Java 8?

This interface is available in Java. util. function package since Java 8 and contains a test(T t) method that evaluates the predicate of a given argument. It returns a boolean value.

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}

53) Have you worked with Streams API?

Streams are introduced in Java 8 and it is not a data structure. It takes inputs from the collections and arrays and provides the result as per pipeline methods without altering the original structure.

For Example below lines of code are first sorting the fruits in alphabetical order and then converting the sorted data in UpperCase.

List.of("apple","banana","mango","orange","grapes").stream().sorted().map(e->e.toUpperCase()).forEach(e->System.out.println(e));

This article provides an in-depth explanation of Java interview questions. These questions are helpful for freshers as well as experienced professionals. To prepare for more interviews visit the interview section.