top of page

The Ultimate Java Interview Questions Guide 2025 : Part-1

Table of Contents

Core Java Fundamentals

Beginner Level

Q1: What is Java and what are its main features?

Java is a high-level, object-oriented programming language developed by Sun Microsystems (now Oracle). Key features include:

  • Platform Independence: "Write once, run anywhere" through JVM

  • Object-Oriented: Supports encapsulation, inheritance, and polymorphism

  • Simple: Clean syntax, automatic memory management

  • Robust: Strong type checking, exception handling

  • Secure: Built-in security features, bytecode verification

  • Multithreaded: Built-in support for concurrent programming

Q2: Explain JVM, JRE, and JDK.

  • JVM (Java Virtual Machine): Runtime environment that executes Java bytecode

  • JRE (Java Runtime Environment): JVM + libraries needed to run Java applications

  • JDK (Java Development Kit): JRE + development tools (compiler, debugger, etc.)

Q3: What are the different data types in Java?

Java has two categories of data types:

Primitive Types:

  • byte (8-bit), short (16-bit), int (32-bit), long (64-bit)

  • float (32-bit), double (64-bit)

  • char (16-bit), boolean (true/false)

Reference Types:

  • Classes, Interfaces, Arrays, Enums

Q4: What is the difference between == and equals() method?

// == compares references for objects, values for primitives
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2);        // false (different objects)
System.out.println(s1.equals(s2));   // true (same content)

// For primitives, == compares values
int a = 10, b = 10;
System.out.println(a == b);          // true

Q5: What is method overloading and overriding?

Method Overloading: Multiple methods with same name but different parameters

public class Calculator {
    public int add(int a, int b) { return a + b; }
    public double add(double a, double b) { return a + b; }
    public int add(int a, int b, int c) { return a + b + c; }
}

Method Overriding: Child class provides specific implementation of parent's method

class Animal {
    public void sound() { System.out.println("Animal makes sound"); }
}

class Dog extends Animal {
    @Override
    public void sound() { System.out.println("Dog barks"); }
}

Intermediate Level

Q6: What are access modifiers in Java?

  • public: Accessible everywhere

  • protected: Accessible within package and by subclasses

  • default: Accessible within package only

  • private: Accessible within class only

Q7: What is the difference between abstract class and interface?

Abstract Class

Interface

Can have concrete methods

Only abstract methods (before Java 8)

Can have instance variables

Only constants (public static final)

Single inheritance

Multiple inheritance

Can have constructors

Cannot have constructors

Can have access modifiers

Methods are public by default

// Abstract class
abstract class Vehicle {
    protected String brand;
    
    public abstract void start();
    
    public void stop() {
        System.out.println("Vehicle stopped");
    }
}

// Interface
interface Drawable {
    void draw();
    
    default void print() {
        System.out.println("Printing...");
    }
}

Q8: What is polymorphism? Explain with example.

Polymorphism allows objects of different types to be treated as objects of a common base type.

class Shape {
    public void draw() { System.out.println("Drawing shape"); }
}

class Circle extends Shape {
    @Override
    public void draw() { System.out.println("Drawing circle"); }
}

class Rectangle extends Shape {
    @Override
    public void draw() { System.out.println("Drawing rectangle"); }
}

public class PolymorphismDemo {
    public static void main(String[] args) {
        Shape[] shapes = {new Circle(), new Rectangle()};
        
        for (Shape shape : shapes) {
            shape.draw(); // Runtime polymorphism
        }
    }
}

Object-Oriented Programming (OOP)

Q9: What are the four pillars of OOP?

  1. Encapsulation: Bundling data and methods, hiding internal details

  2. Inheritance: Creating new classes based on existing ones

  3. Polymorphism: One interface, multiple implementations

  4. Abstraction: Hiding complex implementation details

Q10: What is encapsulation? Provide an example.


public class BankAccount {
    private double balance; // Private field
    private String accountNumber;
    
    // Constructor
    public BankAccount(String accountNumber, double initialBalance) {
        this.accountNumber = accountNumber;
        this.balance = initialBalance;
    }
    
    // Public methods to access private fields
    public double getBalance() {
        return balance;
    }
    
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    
    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }
}

Q11: What is composition vs inheritance?

Inheritance ("is-a" relationship):

class Animal {
    public void eat() { System.out.println("Animal eats"); }
}

class Dog extends Animal {
    public void bark() { System.out.println("Dog barks"); }
}

Composition ("has-a" relationship):

java

class Engine {
    public void start() { System.out.println("Engine started"); }
}

class Car {
    private Engine engine; // Composition
    
    public Car() {
        this.engine = new Engine();
    }
    
    public void startCar() {
        engine.start();
    }
}

Collections Framework

Q12: What is the Java Collections Framework hierarchy?

Collection (Interface)
├── List (Interface)
│   ├── ArrayList
│   ├── LinkedList
│   └── Vector
├── Set (Interface)
│   ├── HashSet
│   ├── LinkedHashSet
│   └── TreeSet
└── Queue (Interface)
    ├── LinkedList
    ├── PriorityQueue
    └── ArrayDeque

Map (Interface)
├── HashMap
├── LinkedHashMap
├── TreeMap
└── Hashtable

Q13: Difference between ArrayList and LinkedList?

ArrayListLinkedListDynamic array implementationDoubly linked listFast random access O(1)Sequential access O(n)Slow insertion/deletion O(n)Fast insertion/deletion O(1)Less memory per elementMore memory (stores pointers)Better for frequent readsBetter for frequent modifications

Q14: What is the difference between HashMap and TreeMap?

// HashMap - Hash table implementation
Map<StringInteger> hashMap = new HashMap<>();
hashMap.put("apple", 10);
hashMap.put("banana", 20);
// No guaranteed order, O(1) operations

// TreeMap - Red-black tree implementation
Map<StringInteger> treeMap = new TreeMap<>();
treeMap.put("apple", 10);
treeMap.put("banana", 20);
// Sorted order, O(log n) operations

Q15: How does HashSet work internally?

HashSet uses HashMap internally where:

  • Elements are stored as keys

  • Values are a dummy PRESENT object

  • Uses hashCode() and equals() for uniqueness

public class HashSetDemo {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("Java");
        set.add("Python");
        set.add("Java"); // Duplicate, won't be added
        
        System.out.println(set.size()); // Output: 2
    }
}

Q16: What is fail-fast and fail-safe iterators?

Fail-fast: Throws ConcurrentModificationException if collection is modified during iteration

List<String> list = new ArrayList<>();
list.add("A");
list.add("B");

Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String item = it.next();
    list.add("C"); // Throws ConcurrentModificationException
}

Fail-safe: Works on copy, doesn't throw exception

ConcurrentHashMap<StringString> map = new ConcurrentHashMap<>();
// Safe for concurrent modifications

Multithreading and Concurrency

Q17: What is multithreading and why is it important?

Multithreading allows concurrent execution of multiple threads within a program, enabling:

  • Better resource utilization

  • Improved performance on multi-core systems

  • Responsive user interfaces

  • Parallel processing of tasks

Q18: How can you create a thread in Java?

Method 1: Extending Thread class

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread running: " + Thread.currentThread().getName());
    }
}

// Usage
MyThread thread = new MyThread();
thread.start();

Method 2: Implementing Runnable interface

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Thread running: " + Thread.currentThread().getName());
    }
}

// Usage
Thread thread = new Thread(new MyRunnable());
thread.start();

Method 3: Using lambda expression

Thread thread = new Thread(() -> {
    System.out.println("Thread running: " + Thread.currentThread().getName());
});
thread.start();

Q19: What is the difference between start() and run() methods?

  • start(): Creates a new thread and calls run() method

  • run(): Executes in the current thread, no new thread created

Thread t = new Thread(() -> System.out.println("Hello"));
t.start(); // Creates new thread
t.run();   // Executes in main thread

Q20: What is synchronization and why is it needed?

Synchronization prevents race conditions when multiple threads access shared resources.

java

class Counter {
    private int count = 0;
    
    // Without synchronization - not thread-safe
    public void increment() {
        count++; // Can cause race condition
    }
    
    // With synchronization - thread-safe
    public synchronized void safeIncrement() {
        count++;
    }
    
    // Synchronized block
    public void blockSynchronized() {
        synchronized (this) {
            count++;
        }
    }
}

Q21: What is deadlock and how to prevent it?

Deadlock occurs when two or more threads are blocked forever, waiting for each other.

// Deadlock example
class DeadlockExample {
    private static Object lock1 = new Object();
    private static Object lock2 = new Object();
    
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (lock1) {
                System.out.println("Thread 1: Holding lock 1");
                try { Thread.sleep(100); } catch (Exception e) {}
                synchronized (lock2) {
                    System.out.println("Thread 1: Holding lock 2");
                }
            }
        });
        
        Thread t2 = new Thread(() -> {
            synchronized (lock2) {
                System.out.println("Thread 2: Holding lock 2");
                try { Thread.sleep(100); } catch (Exception e) {}
                synchronized (lock1) {
                    System.out.println("Thread 2: Holding lock 1");
                }
            }
        });
        
        t1.start();
        t2.start();
    }
}

Prevention strategies:

  • Avoid nested locks

  • Use timeout for lock attempts

  • Always acquire locks in same order

Q22: What is the difference between wait() and sleep()?

wait()

sleep()

Object class method

Thread class method

Releases lock

Doesn't release lock

Must be in synchronized block

Can be called anywhere

Woken up by notify()/notifyAll()

Wakes up after time expires

// wait() example
synchronized (obj) {
    while (condition) {
        obj.wait(); // Releases lock and waits
    }
}

// sleep() example
Thread.sleep(1000); // Sleeps for 1 second, keeps lock

Exception Handling

Q23: What is exception handling in Java?

Exception handling is a mechanism to handle runtime errors, maintaining normal program flow.

Exception hierarchy:

Throwable
├── Exception
│   ├── IOException
│   ├── SQLException
│   └── RuntimeException
│       ├── NullPointerException
│       ├── ArrayIndexOutOfBoundsException
│       └── IllegalArgumentException
└── Error
    ├── OutOfMemoryError
    └── StackOverflowError

Q24: What is the difference between checked and unchecked exceptions?

Checked Exceptions: Must be handled at compile time

// Must handle with try-catch or declare with throws
public void readFile() throws IOException {
    FileReader file = new FileReader("file.txt");
}

Unchecked Exceptions: Runtime exceptions, handling is optional

// Can occur at runtime, handling optional
int result = 10 / 0; // ArithmeticException

Q25: What is try-with-resources?

Automatically closes resources that implement AutoCloseable interface:

// Before Java 7
FileReader reader = null;
try {
    reader = new FileReader("file.txt");
    // Use reader
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// Java 7+ try-with-resources
try (FileReader reader = new FileReader("file.txt")) {
    // Use reader
} catch (IOException e) {
    e.printStackTrace();
} // Automatically closes reader

Q26: Can we have multiple catch blocks?

Yes, and the order matters - more specific exceptions first:

try {
    // Code that may throw exceptions
} catch (FileNotFoundException e) {
    // More specific exception first
    System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
    // More general exception
    System.out.println("IO error: " + e.getMessage());
} catch (Exception e) {
    // Most general exception last
    System.out.println("General error: " + e.getMessage());
}

Memory Management and Garbage Collection

Q27: Explain Java memory structure.

Heap Memory:

  • Young Generation: Eden Space, Survivor Spaces (S0, S1)

  • Old Generation: Long-lived objects

  • Metaspace (Java 8+): Class metadata

Non-Heap Memory:

  • Method Area: Class-level data

  • Code Cache: Compiled native code

  • Stack: Method calls and local variables

Q28: What is garbage collection and how does it work?

Garbage collection automatically manages memory by removing unreferenced objects.

Common GC Algorithms:

  • Serial GC: Single-threaded, suitable for small applications

  • Parallel GC: Multi-threaded, default for server applications

  • G1 GC: Low-latency collector for large heaps

  • ZGC/Shenandoah: Ultra-low latency collectors

// Example of objects eligible for GC
public void createObjects() {
    String s1 = new String("Hello"); // Eligible for GC after method ends
    String s2 = new String("World"); // Eligible for GC after method ends
    
    // s1 and s2 become unreachable when method ends
}

Q29: What are memory leaks in Java and how to prevent them?

Common causes and prevention:

// Memory leak example - listeners not removed
public class MemoryLeakExample {
    private List<EventListener> listeners = new ArrayList<>();
    
    public void addListener(EventListener listener) {
        listeners.add(listener);
        // Should provide removal method
    }
    
    // Proper way
    public void removeListener(EventListener listener) {
        listeners.remove(listener);
    }
}

// Memory leak with static collections
public class StaticCollectionLeak {
    private static List<String> cache = new ArrayList<>();
    
    public void addToCache(String data) {
        cache.add(data); // Never cleared, potential memory leak
    }
}

Prevention strategies:

  • Remove listeners and callbacks

  • Clear collections when not needed

  • Use weak references when appropriate

  • Profile applications regularly

String Manipulation

Q30: Why are Strings immutable in Java?

Strings are immutable for:

  • Security: String parameters can't be changed

  • Thread Safety: No synchronization needed

  • Caching: String pool optimization

  • Hash Code Caching: Consistent hash codes


String s1 = "Hello";
String s2 = s1.concat(" World"); // Creates new string
System.out.println(s1); // Still "Hello"
System.out.println(s2); // "Hello World"

Q31: What is String Pool?

String pool is a storage area in heap memory where string literals are stored:

String s1 = "Hello"; // Stored in string pool
String s2 = "Hello"; // References same object in pool
String s3 = new String("Hello"); // Creates new object in heap

System.out.println(s1 == s2); // true (same reference)
System.out.println(s1 == s3); // false (different objects)
System.out.println(s1.equals(s3)); // true (same content)

// intern() method
String s4 = s3.intern(); // Returns reference from pool
System.out.println(s1 == s4); // tr

Q32: Difference between String, StringBuffer, and StringBuilder?

StringStringBufferStringBuilderImmutableMutableMutableThread-safeThread-safeNot thread-safeSlow concatenationFasterFastestUses String poolDoesn't use poolDoesn't use pool
// String - creates multiple objects
String str = "Hello";
str += " World"; // Creates new string object

// StringBuilder - efficient for single thread
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies existing buffer

// StringBuffer - thread-safe version
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World"); // Thread-safe append

Continue: The Ultimate Java Interview Questions Guide 2025 : Part-2

 
 
 

Comments


bottom of page