Java Interview Questions – Frequently Asked Questions (FAQs)

Complete guide to Java interview questions covering core concepts, OOP principles, collections, multithreading, exception handling, JVM internals, design patterns, and Java 8+ features for software engineering interviews.

21 questions
JavaProgrammingInterviewOOPCollectionsMultithreadingJVMDesign Patterns

Questions & Answers

1What is Java and what are its key features?

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

Key Features:

  1. Platform Independent: Write once, run anywhere (WORA) - compiled code runs on any platform with JVM
  2. Object-Oriented: Follows OOP principles (encapsulation, inheritance, polymorphism, abstraction)
  3. Simple: Easy to learn with clear syntax
  4. Secure: Built-in security features and sandbox execution
  5. Robust: Strong memory management, exception handling, and type checking
  6. Multithreaded: Built-in support for concurrent programming
  7. Portable: Architecture-neutral bytecode
  8. High Performance: Just-In-Time (JIT) compiler for optimization

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

JVM (Java Virtual Machine):

  1. Abstract machine that provides runtime environment
  2. Converts bytecode into machine code
  3. Platform-dependent (different JVM for different OS)

JRE (Java Runtime Environment):

  1. Contains JVM + libraries + other files
  2. Required to run Java applications
  3. Does not include compiler or development tools

JDK (Java Development Kit):

  1. Contains JRE + development tools (compiler, debugger, etc.)
  2. Required to develop Java applications
  3. Includes javac, java, javadoc, jar, etc.

Relationship: JDK = JRE + Development Tools, JRE = JVM + Libraries

3What is the difference between == and equals() in Java?

== Operator:

  1. Compares references (memory addresses) for objects
  2. Compares values for primitive types
  3. Returns true if both references point to the same object

equals() Method:

  1. Compares content/values of objects
  2. Defined in Object class, can be overridden
  3. Default implementation uses == (reference comparison)
  4. String, Integer, etc. override equals() for value comparison

Example:

String s1 = new String("Hello");

String s2 = new String("Hello");

s1 == s2; // false (different references)

s1.equals(s2); // true (same content)

4Explain the main OOP concepts in Java.

1. Encapsulation:

  1. Binding data and methods together in a class
  2. Data hiding using private access modifiers
  3. Access through getters and setters

2. Inheritance:

  1. Creating new classes from existing ones
  2. Code reusability and IS-A relationship
  3. Uses extends keyword
  4. Single inheritance in Java (one parent class)

3. Polymorphism:

  1. One interface, multiple implementations
  2. Compile-time: Method overloading
  3. Runtime: Method overriding

4. Abstraction:

  1. Hiding implementation details
  2. Achieved through abstract classes and interfaces
  3. Shows only essential features

5What is the difference between abstract class and interface?

Abstract Class:

  1. Can have both abstract and concrete methods
  2. Can have instance variables
  3. Can have constructors
  4. Can have static methods
  5. Can have final methods
  6. Supports single inheritance
  7. Uses abstract keyword

Interface (Java 8+):

  1. Can have abstract methods (default public abstract)
  2. Can have default methods (Java 8+)
  3. Can have static methods (Java 8+)
  4. Can have constants (public static final)
  5. Cannot have instance variables or constructors
  6. Supports multiple inheritance
  7. Uses interface keyword

When to use: Use abstract class for IS-A relationship, interface for CAN-DO relationship

6What is the difference between String, StringBuffer, and StringBuilder?

String:

  1. Immutable - cannot be changed once created
  2. Stored in String Pool
  3. Thread-safe (immutable nature)
  4. Slower for concatenation operations

StringBuffer:

  1. Mutable - can be modified
  2. Synchronized - thread-safe
  3. Slower than StringBuilder
  4. Use when thread safety is required

StringBuilder:

  1. Mutable - can be modified
  2. Not synchronized - not thread-safe
  3. Faster than StringBuffer
  4. Use for single-threaded operations

Performance: StringBuilder > StringBuffer > String (for concatenation)

7What are the different types of inheritance in Java?

Java supports the following types of inheritance:

1. Single Inheritance:

  1. One child class extends one parent class
  2. Directly supported in Java

2. Multilevel Inheritance:

  1. Child class becomes parent for another class
  2. Chain of inheritance

3. Hierarchical Inheritance:

  1. Multiple child classes extend one parent class

4. Multiple Inheritance:

  1. NOT directly supported for classes (to avoid diamond problem)
  2. Achieved through interfaces

5. Hybrid Inheritance:

  1. Combination of multiple types
  2. Achieved through interfaces

Note: Java does not support multiple inheritance for classes to avoid ambiguity, but supports it through interfaces.

8What is method overloading and method overriding?

Method Overloading (Compile-time Polymorphism):

  1. Same method name, different parameters
  2. Can differ in: number of parameters, type of parameters, order of parameters
  3. Return type can be same or different
  4. Resolved at compile time
  5. Within the same class

Method Overriding (Runtime Polymorphism):

  1. Same method signature in parent and child class
  2. Child class provides specific implementation
  3. Resolved at runtime
  4. Uses @Override annotation
  5. Cannot override static, final, or private methods

Rules for Overriding:

  1. Method name and parameters must be same
  2. Return type must be same or covariant
  3. Access modifier cannot be more restrictive
  4. Cannot override static methods

9What is the difference between checked and unchecked exceptions?

Checked Exceptions:

  1. Checked at compile-time
  2. Must be handled using try-catch or declared with throws
  3. Extend Exception class (except RuntimeException)
  4. Examples: IOException, SQLException, ClassNotFoundException
  5. For recoverable conditions

Unchecked Exceptions:

  1. Checked at runtime
  2. Not required to be handled or declared
  3. Extend RuntimeException class
  4. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException
  5. For programming errors

Error:

  1. Serious problems that applications should not catch
  2. Examples: OutOfMemoryError, StackOverflowError
  3. Extend Error class

10What is the difference between ArrayList and LinkedList?

ArrayList:

  1. Uses dynamic array internally
  2. Better for random access (O(1))
  3. Slower for insertion/deletion in middle (O(n))
  4. Better for storing and accessing data
  5. Consumes less memory (no pointers)
  6. Not synchronized (not thread-safe)

LinkedList:

  1. Uses doubly linked list internally
  2. Better for insertion/deletion (O(1))
  3. Slower for random access (O(n))
  4. Better for frequent insertions/deletions
  5. Consumes more memory (pointers)
  6. Not synchronized (not thread-safe)

When to use: Use ArrayList for read-heavy operations, LinkedList for write-heavy operations

11What is the difference between HashMap and Hashtable?

HashMap:

  1. Not synchronized - not thread-safe
  2. Allows one null key and multiple null values
  3. Faster performance
  4. Introduced in Java 1.2
  5. Use in single-threaded environment
  6. Iterator is fail-fast

Hashtable:

  1. Synchronized - thread-safe
  2. Does not allow null keys or values
  3. Slower performance (synchronization overhead)
  4. Legacy class (Java 1.0)
  5. Use in multi-threaded environment
  6. Enumerator is not fail-fast

Alternative: Use ConcurrentHashMap for thread-safe operations with better performance than Hashtable

12What is multithreading in Java?

Multithreading is the ability of a CPU to execute multiple threads concurrently.

Thread: Lightweight sub-process, smallest unit of execution

Ways to create threads:

  1. Extending Thread class:
  2. class MyThread extends Thread {
  3. public void run() { ... }
  4. }
  5. Implementing Runnable interface:
  6. class MyRunnable implements Runnable {
  7. public void run() { ... }
  8. }
  9. Using ExecutorService (Java 5+): Recommended approach

Thread States: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED

Benefits: Better CPU utilization, responsive applications, parallel processing

Challenges: Synchronization, deadlock, race conditions

13What is the difference between wait() and sleep()?

wait() method:

  1. Defined in Object class
  2. Must be called from synchronized context
  3. Releases the lock on the object
  4. Used for inter-thread communication
  5. Wakes up by notify() or notifyAll()
  6. Can be interrupted

sleep() method:

  1. Defined in Thread class
  2. Can be called from any context
  3. Does not release the lock
  4. Used to pause execution for a specific time
  5. Wakes up automatically after time expires
  6. Can be interrupted

Example:

// wait() - releases lock

synchronized(obj) {

obj.wait(); // releases lock

}


// sleep() - keeps lock

Thread.sleep(1000); // does not release lock

14What is the difference between synchronized method and synchronized block?

Synchronized Method:

  1. Synchronizes the entire method
  2. Uses synchronized keyword in method signature
  3. Locks on this object (instance method) or class object (static method)
  4. Less flexible
  5. Can reduce performance (locks entire method)

Synchronized Block:

  1. Synchronizes only a specific block of code
  2. Uses synchronized keyword with object reference
  3. Can lock on any object
  4. More flexible and efficient
  5. Better performance (locks only critical section)

Example:

// Synchronized method

public synchronized void method() { ... }


// Synchronized block

public void method() {

synchronized(this) {

// critical section

}

}

15What is garbage collection in Java?

Garbage Collection (GC) is the automatic memory management process in Java.

How it works:

  1. JVM automatically identifies and removes unused objects
  2. Runs in background thread
  3. Frees memory occupied by unreachable objects

GC Algorithms:

  1. Serial GC: Single-threaded, for small applications
  2. Parallel GC: Multiple threads, default for server applications
  3. G1 GC: Low latency, for large heap sizes
  4. ZGC: Ultra-low latency (Java 11+)

Object becomes eligible for GC when:

  1. No references pointing to it
  2. All references are null
  3. Island of isolation (circular references with no external reference)

Methods: System.gc() (suggests GC, not guaranteed), finalize() (deprecated in Java 9)

16What are Java 8 features?

Java 8 introduced major features:

1. Lambda Expressions:

  1. Anonymous functions
  2. Enables functional programming
  3. Syntax: (parameters) -> expression

2. Stream API:

  1. Process collections in functional style
  2. Operations: filter, map, reduce, collect
  3. Lazy evaluation

3. Functional Interfaces:

  1. Interfaces with single abstract method
  2. @FunctionalInterface annotation
  3. Examples: Predicate, Function, Consumer, Supplier

4. Default Methods:

  1. Methods with implementation in interfaces
  2. Backward compatibility

5. Optional Class:

  1. Container for null-safe operations
  2. Prevents NullPointerException

6. Date/Time API:

  1. java.time package
  2. Immutable and thread-safe
  3. LocalDate, LocalTime, LocalDateTime

17What is the difference between List, Set, and Map?

List:

  1. Ordered collection (maintains insertion order)
  2. Allows duplicate elements
  3. Index-based access
  4. Examples: ArrayList, LinkedList, Vector
  5. Implements Collection interface

Set:

  1. Unordered collection (no guaranteed order)
  2. Does not allow duplicates
  3. No index-based access
  4. Examples: HashSet, LinkedHashSet, TreeSet
  5. Implements Collection interface

Map:

  1. Key-value pairs
  2. Does not allow duplicate keys
  3. Each key maps to exactly one value
  4. Examples: HashMap, LinkedHashMap, TreeMap, Hashtable
  5. Does NOT implement Collection interface

Summary: List = ordered + duplicates, Set = no duplicates, Map = key-value pairs

18What is the difference between final, finally, and finalize?

final keyword:

  1. Variable: Cannot be reassigned (constant)
  2. Method: Cannot be overridden
  3. Class: Cannot be extended
  4. Compile-time constraint

finally block:

  1. Used with try-catch
  2. Always executes (except System.exit())
  3. Used for cleanup code
  4. Runtime execution

finalize() method:

  1. Method in Object class
  2. Called by GC before object is destroyed
  3. Deprecated in Java 9
  4. Not guaranteed to execute
  5. Use try-with-resources instead

Example:

final int x = 10; // constant

try { ... }

finally { ... } // always executes

protected void finalize() { ... } // deprecated

19What is the difference between throw and throws?

throw keyword:

  1. Used to explicitly throw an exception
  2. Used inside a method
  3. Throws a single exception
  4. Used with instance of exception

throws keyword:

  1. Used to declare exceptions that a method might throw
  2. Used in method signature
  3. Can declare multiple exceptions
  4. Used with exception class names

Example:

// throws - declares exception

public void method() throws IOException {

// throw - throws exception

throw new IOException("Error occurred");

}

Purpose: throw = create and throw exception, throws = declare possible exceptions

20What are design patterns in Java?

Design Patterns are reusable solutions to common software design problems.

Creational Patterns:

  1. Singleton: Single instance of a class
  2. Factory: Creates objects without specifying exact class
  3. Builder: Constructs complex objects step by step

Structural Patterns:

  1. Adapter: Allows incompatible interfaces to work together
  2. Decorator: Adds behavior to objects dynamically
  3. Facade: Provides simplified interface to complex subsystem

Behavioral Patterns:

  1. Observer: Notifies multiple objects about state changes
  2. Strategy: Defines family of algorithms, makes them interchangeable
  3. Template Method: Defines skeleton of algorithm in base class

Benefits: Code reusability, maintainability, proven solutions

21What is the Singleton pattern and how to implement it?

Singleton Pattern ensures only one instance of a class exists.

Implementation Approaches:

1. Eager Initialization:


class Singleton {
private static Singleton instance = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
return instance;
}
}


2. Lazy Initialization (Thread-safe):


class Singleton {

private static volatile Singleton instance;


private Singleton() {}


public static Singleton getInstance() {

if (instance == null) {

synchronized (Singleton.class) {

if (instance == null) {

instance = new Singleton();

}

}

}

return instance;

}

}


3. Bill Pugh Solution (Recommended):


class Singleton {
private Singleton() {}

private static class SingletonHelper {
private static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
return SingletonHelper.INSTANCE;
}
}