Master These Most Frequently Asked Java Interview Questions Before Your Next Interview in 2025

Java Interview Questions & Answers for Experienced Developers 2025

Java is one of the most widely used programming languages in the world, and mastering its core concepts is crucial for acing technical interviews. In this blog, we’ll cover some of the most frequently asked Java interview questions, helping you prepare efficiently. For more interview tips and resources, check out our interviews page.


1. JDK, JRE, and JVM – What’s the Difference?

Understanding the core components of the Java ecosystem is crucial.

  • JDK (Java Development Kit): The JDK is a comprehensive software development kit that provides all the tools needed to develop, compile, and run Java applications. It includes the JRE, a Java compiler (javac), a debugger (jdb), and other development utilities. Think of it as the complete toolbox for a Java developer.
  • JRE (Java Runtime Environment): The JRE provides the necessary environment to execute Java applications. It includes the JVM and the core Java class libraries. It's what you need to run pre-compiled Java code.
  • JVM (Java Virtual Machine): The JVM is the heart of Java's platform independence. It's an abstract machine that executes Java bytecode. The JVM translates the bytecode into instructions that the underlying operating system can understand. Different JVM implementations exist for various operating systems, allowing Java programs to run on any platform without modification.

Example: Imagine you're building a house. The JDK is like the architect's office with all the blueprints and tools. The JRE is like the construction crew that uses those blueprints. The JVM is like the specific tools the crew uses, adapting to the terrain (different operating systems) to build the house.

2. Why is Java Platform-Independent?

Java's platform independence stems from its "compile once, run anywhere" philosophy. Java code is not compiled directly into machine code for a specific operating system. Instead, it's compiled into an intermediate form called bytecode. This bytecode is then executed by the JVM. Since the JVM acts as an intermediary, it handles the translation of bytecode into machine-specific instructions. Therefore, the same Java bytecode can run on any platform that has a JVM implementation.

Example: A Java program compiled on Windows can run on Linux or macOS without any changes, as long as those systems have a JVM installed.

3. Abstract Class vs. Interface

Both abstract classes and interfaces are used to achieve abstraction in Java, but they have key differences:

Feature Abstract Class Interface 
Methods Can have both abstract & concrete methods Only abstract methods (before Java 8) or default/static methods (Java 8+)
Fields Can have instance variables Only constants (static & final) 
Multiple Inheritance Not supported for classesSupported for interfaces
ConstructorCan have a constructorCannot have a constructor
InheritanceA class can extend only one abstract classA class can implement multiple interfaces

Example: An Animal abstract class might define common characteristics like eat() and sleep(), while specific animals like Dog and Cat extend Animal and implement these methods in their own way. An interface like Flyable could be implemented by both Bird and Airplane, defining the fly() method.

4. Role of final, finally, and finalize

These keywords serve distinct purposes:

  • final: Used to restrict modification. It can be applied to variables (making them constants), methods (preventing overriding), and classes (preventing inheritance).
    • final variable: final int x = 10; x cannot be reassigned.
    • final method: final void myMethod() {} myMethod cannot be overridden.
    • final class: final class MyClass {} MyClass cannot be inherited.
  • finally: A block of code in a try-catch block that is always executed, regardless of whether an exception is thrown or caught. It's typically used for cleanup operations like closing resources.
  • finalize(): A method of the Object class that is called by the garbage collector before an object is reclaimed. It's used for cleanup tasks but its behavior is unpredictable and should be used with caution.

Example:

try {
    // Code that might throw an exception
    int result = 10 / 0; 
} catch (ArithmeticException e) {
    System.out.println("Division by zero!");
} finally {
    System.out.println("This will always be executed.");
    // Close resources here
}

5. Stack vs. Heap Memory

Java memory is divided into two main areas:

Stack MemoryHeap Memory
Stores local variables, method call frames, and primitive values.Stores objects and their instance variables.
Fast accessSlower access
Memory deallocated automatically after method execution (LIFO).Memory managed by the Garbage Collector.
Thread-specific. Each thread has its own stack.Shared by all threads.

Example: When a method is called, its local variables and the method call frame are pushed onto the stack. When the method returns, they are popped off. Objects created using new are stored in the heap.

6. Method Overloading vs. Method Overriding

These concepts relate to polymorphism:

  • Method Overloading: Defining multiple methods in the same class with the same name but different parameters (number, type, or order). It's a form of compile-time polymorphism. The compiler decides which method to call based on the arguments.
    • Example:
public class Calculator {
    public int add(int a, int b) { return a + b; }
    public double add(double a, double b) { return a + b; }
}
  • Method Overriding: Redefining a method inherited from a superclass in a subclass. The subclass provides its own implementation of the method. It's a form of runtime polymorphism. The JVM decides which method to call at runtime based on the object's actual type.
    • Example:
class Animal {
    public void makeSound() { System.out.println("Generic animal sound"); }
}
 
class Dog extends Animal {
    @Override
    public void makeSound() { System.out.println("Woof!"); }
}

7. Difference Between Private and Protected Access Modifiers

Access modifiers control the visibility and accessibility of class members:

  • Private: Accessible only within the same class. No other class, not even a subclass, can access private members.
  • Protected: Accessible within the same package and by subclasses (even if they are in a different package).

Example: If a variable name is declared private in the Person class, only methods within the Person class can access it. If it's declared protected, subclasses of Person can also access it, even if they are in a different package.

8. What is Constructor Overloading?

Constructor overloading is similar to method overloading. It involves defining multiple constructors in a class with different parameter lists. This allows you to create objects of the class in different ways, initializing them with different sets of values.

Example:

public class Person {
    private String name;
    private int age;
 
    public Person(String name) {
        this.name = name;
    }
 
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

9. Purpose of the super Keyword

The super keyword is used to refer to the superclass (parent class) from within a subclass. It has three main uses:

  1. Accessing superclass members: super.variableName or super.methodName()
  2. Calling the superclass constructor: super() (must be the first statement in the subclass constructor)
  3. Calling a superclass method that has been overridden: super.methodName()

Example:

class Animal {
    String name;
    Animal(String name) { this.name = name; }
    void eat() { System.out.println("Animal is eating"); }
}
 
class Dog extends Animal {
    Dog(String name) {
        super(name); // Calling the superclass constructor
    }
    @Override
    void eat() {
        super.eat(); // Calling the superclass method
        System.out.println("Dog is eating bones");
    }
}

10. What are Static Blocks in Java?

  • A static block is a block of code inside a class that is executed once when the class is loaded into memory.
  • Used to initialize static variables.
  • Executes before the main method.

Example:

class Example {
    static int num;
    static {
        num = 100;
        System.out.println("Static block executed. num = " + num);
    }
    public static void main(String[] args) {
        System.out.println("Main method executed.");
    }
}

Output:

Static block executed. num = 100
Main method executed.

11. What is the Use of the this Keyword in Constructors?

  • The this keyword refers to the current instance of the class.
  • Used to differentiate instance variables from parameters if they have the same name.
  • Can also be used to call another constructor in the same class.

Example:

class Example {
    int a;
    Example(int a) {
        this.a = a;  // 'this' differentiates instance variable from parameter
    }
    void display() {
        System.out.println("Value of a: " + a);
    }
    public static void main(String[] args) {
        Example obj = new Example(10);
        obj.display();
    }
}

Output:

Value of a: 10

12. Object-Oriented Features Supported by Java

Java supports four main Object-Oriented Programming (OOP) features:

  1. Encapsulation: Wrapping data (variables) and code (methods) into a single unit (class).

    class Person {
        private String name; // Private variable
        
        public void setName(String name) { // Setter method
            this.name = name;
        }
        public String getName() { // Getter method
            return name;
        }
    }
  2. Inheritance: Acquiring properties and behaviors from a parent class.

    class Animal {
        void makeSound() {
            System.out.println("Animal makes a sound");
        }
    }
    class Dog extends Animal {
        void bark() {
            System.out.println("Dog barks");
        }
    }
  3. Polymorphism: A method behaves differently based on the object that calls it.

    class Animal {
        void makeSound() {
            System.out.println("Animal sound");
        }
    }
    class Dog extends Animal {
        void makeSound() { // Method Overriding
            System.out.println("Dog barks");
        }
    }
  4. Abstraction: Hiding implementation details and only showing functionality.

    abstract class Vehicle {
        abstract void start();
    }
    class Car extends Vehicle {
        void start() {
            System.out.println("Car starts with a key");
        }
    }

13. Access Specifiers in Java

Access Modifier Scope 
private Only within the class 
default Within the same package 
protected Same package + subclasses 
public Accessible everywhere 

Example:

class Example {
    private int privateVar = 10;
    protected int protectedVar = 20;
    public int publicVar = 30;
    int defaultVar = 40; // Default access modifier
}

14. Composition vs. Inheritance

Composition (HAS-A relationship):

  • One class contains an object of another class.
  • More flexible than inheritance as it allows changing behavior dynamically.

Example:

class Engine {
    void start() {
        System.out.println("Engine is starting...");
    }
}
class Car {
    private Engine engine = new Engine(); // Composition
    void startCar() {
        engine.start();
        System.out.println("Car started");
    }
}

Inheritance (IS-A relationship):

  • A class inherits another class’s behavior.

Example:

class Animal {
    void eat() {
        System.out.println("This animal eats food");
    }
}
class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}

15. Purpose of an Abstract Class

  • Provides a base class for subclasses.
  • Can have both abstract and concrete methods.
  • Cannot be instantiated directly.

Example:

abstract class Animal {
    abstract void makeSound(); // Abstract method
    void sleep() {
        System.out.println("Sleeping...");
    }
}
class Dog extends Animal {
    void makeSound() {
        System.out.println("Dog barks");
    }
}

Ready to Ace Your Next Tech Interview?

Explore our comprehensive interview resources, covering everything from common interview questions to specialized AI interview prep.

Explore Interview Resources

AI Interview Prep

16. Constructor vs. Method in Java

  • A constructor is called automatically when an object is created, whereas methods are explicitly called.
  • Constructors initialize objects, while methods define behaviors.
  • Example:
    class Car {
        String model;
        
        // Constructor
        Car(String model) {
            this.model = model;
        }
        
        // Method
        void displayModel() {
            System.out.println("Car model: " + model);
        }
    }
     
    public class Test {
        public static void main(String[] args) {
            Car myCar = new Car("Toyota"); // Constructor is called
            myCar.displayModel(); // Method is called explicitly
        }
    }

17. The Diamond Problem in Java

  • Occurs when a class inherits from two classes that have the same method.
  • Solution: Java doesn’t support multiple inheritance with classes but allows it with interfaces using default methods.
  • Example:
    interface A {
        default void show() {
            System.out.println("A's show method");
        }
    }
     
    interface B {
        default void show() {
            System.out.println("B's show method");
        }
    }
     
    class C implements A, B {
        public void show() {
            A.super.show(); // Resolving ambiguity
        }
    }
     
    public class Test {
        public static void main(String[] args) {
            C obj = new C();
            obj.show();
        }
    }

18. Local vs. Instance Variables

  • Local variables exist only inside methods and are not accessible outside.
  • Instance variables belong to an object and persist throughout its lifetime.
  • Example:
    class Person {
        String name; // Instance variable
        
        void setName(String newName) {
            String tempName = newName; // Local variable
            name = tempName;
        }
    }

19. What is a Marker Interface?

  • An interface without methods, used to provide metadata (e.g., Serializable).
  • Example:
    import java.io.Serializable;
     
    class Employee implements Serializable {
        int id;
        String name;
    }

20. How Does Java Achieve Polymorphism?

  • Method Overloading (Compile-time polymorphism)
    class MathUtils {
        int add(int a, int b) {
            return a + b;
        }
        
        double add(double a, double b) {
            return a + b;
        }
    }
  • Method Overriding (Runtime polymorphism)
    class Animal {
        void makeSound() {
            System.out.println("Animal makes a sound");
        }
    }
     
    class Dog extends Animal {
        void makeSound() {
            System.out.println("Dog barks");
        }
    }

21. Why are Strings Immutable in Java?

  • For security, caching, and synchronization reasons.
  • Example:
    String s1 = "Hello";
    String s2 = s1;
    s1 = "World";
    System.out.println(s2); // Output: Hello

22. Difference Between Creating Strings Using new() vs. Literals

  • Using literals: Stored in the String Pool (better performance).
  • Using new: Creates a new object in the heap.
  • Example:
    String s1 = "Hello"; // String pool
    String s2 = new String("Hello"); // Heap memory

23. What is the Collections Framework?

  • A set of classes and interfaces for working with collections like lists, sets, and maps.
  • Example:
    List<String> names = new ArrayList<>();
    names.add("Alice");
    names.add("Bob");

24. ArrayList vs. LinkedList

FeatureArrayListLinkedList
StorageDynamic arrayDoubly linked list
AccessFast (O(1))Slow (O(n))
Insert/DeleteSlow (O(n))Fast (O(1))

25. HashMap vs. TreeMap

  • HashMap: Unordered, O(1) lookup time.
  • TreeMap: Ordered, O(log n) lookup time.
  • Example:
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "One");

26. Checked vs. Unchecked Exceptions

  • Checked: Must be handled (IOException).
  • Unchecked: Runtime exceptions (NullPointerException).
  • Example:
    try {
        FileReader file = new FileReader("file.txt"); // Checked Exception
    } catch (IOException e) {
        e.printStackTrace();
    }

27. What is a Thread? Lifecycle Stages

  • A thread is a lightweight process with states:
    1. New
    2. Runnable
    3. Blocked
    4. Waiting
    5. Terminated
  • Example:
    class MyThread extends Thread {
        public void run() {
            System.out.println("Thread is running");
        }
    }

28. What is a Deadlock? How to Avoid It?

  • Occurs when two threads are waiting for each other indefinitely.
  • Avoidance: Use proper synchronization, lock ordering, or timeouts.
  • Example:
    synchronized (lock1) {
        synchronized (lock2) {
            // Deadlock risk
        }
    }

29. Difference Between notify() and notifyAll()

  • notify(): Wakes one thread.
  • notifyAll(): Wakes all waiting threads.
  • Example:
    synchronized (obj) {
        obj.notify();
    }

Conclusion

Mastering these Java interview questions will help you build a strong foundation and boost your confidence. Preparing with real-world examples and coding practice will give you an edge over other candidates. For more tips on how to prepare for technical interviews, including AI-related questions, visit our AI Interview page. And don't forget to use our resume analyzer to make sure your resume stands out!

Make Your Resume Shine

Use our powerful resume analyzer to identify areas for improvement and ensure your resume stands out from the crowd.

Analyze My Resume



Related Posts