Skip to main content

Java Interview Questions Guide

A comprehensive collection of commonly asked Java interview questions organized by difficulty level.

Table of Contents​


Easy Questions​

1. What is Java?​

Answer: Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now Oracle). It follows the "write once, run anywhere" (WORA) principle through the Java Virtual Machine (JVM).

2. What are the main features of Java?​

Answer:

  • Platform independence
  • Object-oriented programming
  • Automatic memory management (Garbage Collection)
  • Multithreading support
  • Security
  • Robustness
  • Simple syntax

3. What is the difference between JDK, JRE, and JVM?​

Answer:

  • 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.)

4. What are the primitive data types in Java?​

Answer: 8 primitive types:

  • byte (1 byte)
  • short (2 bytes)
  • int (4 bytes)
  • long (8 bytes)
  • float (4 bytes)
  • double (8 bytes)
  • char (2 bytes)
  • boolean (1 bit)

5. What is the difference between == and equals() method?​

Answer:

  • == compares references (memory addresses) for objects, values for primitives
  • equals() compares the actual content/value of objects (when properly overridden)

6. What is method overloading?​

Answer: Method overloading allows multiple methods with the same name but different parameters (different number, type, or order of parameters) within the same class.

7. What is the static keyword?​

Answer: static means the member belongs to the class rather than any instance. Static members can be accessed without creating an object of the class.

8. What is inheritance in Java?​

Answer: Inheritance allows a class (child/subclass) to inherit properties and methods from another class (parent/superclass) using the extends keyword.

9. What is polymorphism?​

Answer: Polymorphism allows objects of different types to be treated as objects of a common base type. It includes method overriding (runtime) and method overloading (compile-time).

10. What is encapsulation?​

Answer: Encapsulation is the bundling of data (variables) and methods that operate on that data within a single unit (class), while hiding the internal implementation details.


Medium Questions​

1. What is the difference between abstract class and interface?​

Answer:

  • Abstract Class: Can have both abstract and concrete methods, constructors, instance variables, access modifiers
  • Interface: Only abstract methods (before Java 8), public by default, no constructors, only static final variables

2. What are the access modifiers in Java?​

Answer:

  • private: Accessible only within the same class
  • default (package-private): Accessible within the same package
  • protected: Accessible within package and subclasses
  • public: Accessible everywhere

3. What is exception handling in Java?​

Answer: Exception handling uses try-catch-finally blocks to handle runtime errors gracefully:

try {
// risky code
} catch (SpecificException e) {
// handle exception
} finally {
// cleanup code
}

4. What is the difference between checked and unchecked exceptions?​

Answer:

  • Checked Exceptions: Must be handled at compile time (IOException, SQLException)
  • Unchecked Exceptions: Runtime exceptions that don't need explicit handling (NullPointerException, ArrayIndexOutOfBoundsException)

5. What is multithreading and how do you create threads?​

Answer: Multithreading allows concurrent execution of multiple threads. Two ways to create threads:

  1. Extend Thread class
  2. Implement Runnable interface

6. What is synchronization in Java?​

Answer: Synchronization prevents thread interference and memory consistency errors by allowing only one thread to access a shared resource at a time using synchronized keyword.

7. What are Collections in Java?​

Answer: Collections Framework provides data structures like List, Set, Map, and Queue with implementations like ArrayList, HashSet, HashMap, etc.

8. What is the difference between ArrayList and LinkedList?​

Answer:

  • ArrayList: Dynamic array, fast random access, slower insertion/deletion
  • LinkedList: Doubly linked list, slower random access, faster insertion/deletion

9. What is garbage collection?​

Answer: Automatic memory management that reclaims memory occupied by objects that are no longer referenced, preventing memory leaks.

10. What is the finalize() method?​

Answer: A method called by garbage collector before destroying an object. Used for cleanup operations but not recommended due to unpredictable timing.

11. What is method overriding?​

Answer: Subclass provides a specific implementation of a method already defined in its parent class. Uses @Override annotation and follows runtime polymorphism.

12. What is the super keyword?​

Answer: super refers to the immediate parent class object. Used to access parent class methods, constructors, and variables.


Hard Questions​

1. Explain the Java Memory Model and different memory areas​

Answer: Java memory is divided into:

  • Heap: Objects and instance variables (Young Generation, Old Generation)
  • Stack: Method calls and local variables
  • Method Area: Class-level data, static variables, method bytecode
  • PC Register: Current executing instruction
  • Native Method Stack: Native method calls

2. What are the different types of classloaders?​

Answer:

  • Bootstrap ClassLoader: Loads core Java classes from rt.jar
  • Extension ClassLoader: Loads classes from ext directory
  • Application ClassLoader: Loads classes from classpath
  • Custom ClassLoaders: User-defined loaders

3. Explain the concept of immutable objects and how to create them​

Answer: Immutable objects cannot be modified after creation. To create:

  • Make class final
  • Make all fields private final
  • Don't provide setter methods
  • Initialize all fields via constructor
  • Return defensive copies of mutable objects

4. What is reflection and when would you use it?​

Answer: Reflection allows runtime inspection and manipulation of classes, methods, and fields. Used in frameworks, serialization, testing frameworks, and dependency injection.

5. Explain different types of nested classes​

Answer:

  • Static Nested Class: Can be instantiated without outer class instance
  • Inner Class: Requires outer class instance, has access to outer class members
  • Local Class: Defined inside a method
  • Anonymous Class: Unnamed class, typically used with interfaces

6. What are generics and type erasure?​

Answer: Generics provide type safety at compile time. Type erasure removes generic type information at runtime for backward compatibility, replacing with raw types or bounds.

7. Explain the producer-consumer problem and its solution​

Answer: Classic synchronization problem where producers generate data and consumers process it. Solutions include:

  • wait() and notify()
  • BlockingQueue
  • Semaphore
  • ReentrantLock with Condition

8. What is the difference between fail-fast and fail-safe iterators?​

Answer:

  • Fail-fast: Throws ConcurrentModificationException if collection is modified during iteration (ArrayList)
  • Fail-safe: Creates a copy and iterates over it, allowing safe modification (ConcurrentHashMap)

9. Explain different garbage collection algorithms​

Answer:

  • 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

10. What is the happens-before relationship?​

Answer: Defines ordering constraints between memory operations in concurrent programming. Ensures that certain operations are visible to other threads in a specific order.

11. Explain the Singleton pattern and its thread-safe implementations​

Answer: Ensures only one instance of a class exists. Thread-safe implementations:

  • Synchronized method
  • Double-checked locking
  • Enum singleton
  • Static inner class (Bill Pugh)

12. What are weak, soft, and phantom references?​

Answer:

  • Strong Reference: Normal references, prevent GC
  • Weak Reference: Eligible for GC even if referenced
  • Soft Reference: GC only when memory is low
  • Phantom Reference: Used for cleanup actions, already GC'd objects

13. Explain the Fork/Join framework​

Answer: Parallel computing framework that uses work-stealing algorithm. Tasks are recursively split into smaller subtasks and executed in parallel using ForkJoinPool.

14. What is the difference between Callable and Runnable?​

Answer:

  • Runnable: run() method, returns void, cannot throw checked exceptions
  • Callable: call() method, returns a value, can throw checked exceptions

15. Explain Java 8+ features (Lambda, Streams, Optional)​

Answer:

  • Lambda Expressions: Anonymous functions for functional programming
  • Streams API: Functional-style operations on collections
  • Optional: Container to avoid null pointer exceptions
  • Method References: Shorthand for lambda expressions

Tips for Interview Success​

  1. Understand the fundamentals - Master OOP concepts, data structures, and basic syntax
  2. Practice coding - Be ready to write code on paper or whiteboard
  3. Know the Collections framework - Understand when to use which collection
  4. Be familiar with concurrency - Threading, synchronization, and concurrent collections
  5. Understand JVM internals - Memory management, garbage collection, classloading
  6. Stay updated - Know modern Java features (Java 8+)
  7. Practice system design - For senior positions, understand architectural patterns

Remember to not just memorize answers but understand the concepts deeply. Good luck with your interview preparation!