Top 50 Java Interview Questions and Answers

I
InterviPrep Engineering Team
Nov 29, 2023
18 min read
Top 50 Java Interview Questions and Answers

Top 50 Java Interview Questions and Answers (2024 Edition)

Java remains the undisputed king of enterprise software. Companies like Amazon, Netflix, Apple, and large financial institutions rely on Java's unmatched stability, performance, and massive ecosystem (specifically Spring Boot) to power their backend services.

Because Java is a mature, strictly typed language, interviews are highly structured. You will not only be tested on Data Structures, but you will also face grueling questions regarding the internal workings of the JVM, memory management, and concurrent programming.

In this exhaustive 2,000+ word guide, we have compiled the Top 50 Java Interview Questions, breaking them down from core OOP principles to advanced multithreading architectures.


Part 1: Core OOP and Fundamentals (Questions 1-15)

These questions test your baseline understanding of object-oriented design and the Java language syntax.

1. What is the difference between an Abstract Class and an Interface?

This is the most frequently asked Java question.

  • Interface: Prior to Java 8, interfaces could only contain abstract methods (no implementation). Now they can have default and static methods. A class can implement multiple interfaces. Interfaces cannot have state (instance variables).
  • Abstract Class: Can contain both abstract and concrete methods. Can hold state (instance variables). A class can only extend one abstract class.

2. Explain String, StringBuilder, and StringBuffer.

  • String: Immutable. Every time you concatenate strings (str + "a"), a brand new object is created in the String Pool, which is terrible for performance in loops.
  • StringBuilder: Mutable. Allows for efficient string manipulation without creating new objects. It is not thread-safe.
  • StringBuffer: Mutable and thread-safe (methods are synchronized), but slower than StringBuilder.

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

  • == compares object references (memory addresses). Do these two variables point to the exact same object in the heap?
  • .equals() is a method used to compare the actual value (state) of the objects. It must be explicitly overridden in your custom classes to work properly.

4. What is the contract between hashCode() and equals()?

If you override equals(), you must override hashCode().

  • If two objects are equal according to equals(), they must return the same integer from hashCode().
  • If two objects have the same hashCode(), they are not necessarily equal (this is called a hash collision).

5. Does Java support Pass-by-Value or Pass-by-Reference?

Java is strictly Pass-by-Value. When you pass an object to a method, you are passing a copy of the reference to that object. You can modify the object's state inside the method, but you cannot reassign the original reference to point to a brand new object.

6-15. Essential Syntax

  • static keyword: Belongs to the class, not the instance.
  • final keyword: A final variable cannot be reassigned. A final method cannot be overridden. A final class cannot be extended.
  • Access Modifiers: Understand private, default (package-private), protected, and public.

Part 2: JVM Architecture & Memory Management (Questions 16-30)

Senior engineers must know what happens when they run java -jar application.jar.

16. Explain the architecture of the JVM.

The JVM acts as a bridge between your compiled bytecode (.class files) and the underlying operating system.

  1. Class Loader Subsystem: Loads, links, and initializes class files into memory.
  2. Runtime Data Areas: Includes the Heap (where objects live), the Stack (where method calls and local variables live), the Method Area (metadata), and the Program Counter Register.
  3. Execution Engine: Contains the Interpreter and the JIT (Just-In-Time) Compiler, which translates bytecode into native machine code for execution.

17. How does Garbage Collection (GC) work in Java?

Garbage Collection automatically frees memory by destroying unreachable objects.

  • The Heap Structure: The heap is divided into the Young Generation (Eden space, Survivor spaces S0/S1) and the Old (Tenured) Generation.
  • Minor GC: When Eden fills up, surviving objects are moved to Survivor spaces.
  • Major/Full GC: When objects survive multiple Minor GCs, they are promoted to the Old Generation. When the Old Generation fills up, a Major GC occurs, which is expensive and causes "Stop-The-World" pauses.

18. What causes a OutOfMemoryError vs. a StackOverflowError?

  • OutOfMemoryError: Occurs when the Heap space is full (e.g., loading a massive file into a List and keeping the reference).
  • StackOverflowError: Occurs when the Stack space is exhausted, almost always due to infinite recursion (a method calling itself without a base case).

19. What is the purpose of the volatile keyword?

It is used in multithreading. By marking a variable as volatile, you ensure that the value is always read directly from the main memory, rather than from a thread's local CPU cache. It guarantees visibility of changes across threads.


Part 3: Collections Framework (Questions 31-40)

You must know which data structure to choose for performance optimization.

31. What is the difference between ArrayList and LinkedList?

  • ArrayList: Backed by a dynamic array. Fast $O(1)$ random access (e.g., list.get(5)). Slow $O(N)$ insertions/deletions in the middle of the list, as elements must be shifted.
  • LinkedList: Backed by a doubly-linked list. Slow $O(N)$ random access. Fast $O(1)$ insertions/deletions if you already have the node reference.

32. How does a HashMap work internally?

Before Java 8, it used an array of linked lists.

  1. It calls hashCode() on the key to calculate an array index (bucket).
  2. If multiple keys hash to the same bucket (collision), it stores them in a linked list.
  3. In Java 8+, if a bucket's linked list grows past 8 elements, it transforms into a Balanced Binary Tree (Red-Black Tree) to improve worst-case lookup from $O(N)$ to $O(\log N)$.

33. HashMap vs. ConcurrentHashMap?

  • HashMap is not thread-safe. If multiple threads modify it simultaneously, it can enter an infinite loop during resizing.
  • ConcurrentHashMap is thread-safe. Instead of locking the entire map (like the legacy HashTable), it uses lock striping, locking only the specific bucket being updated, allowing high concurrent read/write throughput.

Part 4: Concurrency & Multithreading (Questions 41-50)

For Senior Backend roles, you will be drilled heavily on this section.

41. How do you create a Thread in Java?

  1. Extend the Thread class.
  2. Implement the Runnable interface.
  3. Implement the Callable interface (allows you to return a value and throw checked exceptions, unlike Runnable).

42. What is an ExecutorService?

Manually creating threads (new Thread()) is expensive because it requires OS resources. The ExecutorService provides a Thread Pool. Instead of destroying a thread when a task is done, the thread is returned to the pool to be reused.

43. Explain the difference between sleep() and wait().

  • sleep(): A static method of the Thread class. It pauses the thread for a specified time but does not release the lock it holds.
  • wait(): An instance method of the Object class. It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify().

44. What is a Deadlock and how do you prevent it?

A deadlock occurs when Thread A holds Lock 1 and waits for Lock 2, while Thread B holds Lock 2 and waits for Lock 1. Both freeze permanently.

  • Prevention: The easiest way to prevent deadlocks is to enforce a strict ordering of lock acquisition. If all threads must always acquire Lock 1 before Lock 2, a deadlock cannot occur.

45-50. Advanced Frameworks (Spring Boot)

While not core Java, enterprise interviews always include Spring Boot:

  • Dependency Injection (DI) & Inversion of Control (IoC): How Spring manages the lifecycle of beans.
  • @Transactional: How Spring manages database transactions and rollback behavior.
  • Spring MVC: The request flow from the DispatcherServlet to the Controller.

Conclusion & Next Steps

Java interviews require a delicate balance. You must be able to solve LeetCode algorithms, but you must also deeply understand the theoretical architecture of the JVM and concurrent programming.

Review your Collections framework, understand the internal mechanics of HashMap, and practice writing thread-safe code. Use InterviPrep AI to simulate realistic Java technical rounds, complete with probing questions on GC tuning and multithreading architectures.

Share this guide: