Data Structures and Algorithms

Top 25 Java Interview Questions and Answers for Software Engineers

Java continues to dominate enterprise, backend, and Android development, making it one of the most in-demand skills for software engineers. Whether you’re preparing for FAANG interviews or mid-sized product companies, these 25 most frequently asked Java interview questions will help you master concepts, coding challenges, and JVM internals.

Before diving in, stay ahead in your preparation with free Java & DSA practice resources: Sign up here.

  1. What are the main features of Java?

Java is built on the principle of WORA (Write Once, Run Anywhere).

Key Features:

  • Object-Oriented → Uses classes and objects.
  • Platform Independent → Bytecode runs on JVM across OS.
  • Robust & Secure → Memory management, exception handling.
  • Multithreaded → Handles multiple threads at once.
  • Portable → Runs on any device with JVM.

Diagram: Java Features Overview

[ Java Program ]

       ↓ Compile

[ Bytecode ] → [ JVM ] → [ Any OS ]

 

  1. Difference between JDK, JRE, and JVM

Component

Full Form

Role

JDK

Java Development Kit

Tools for development (javac, debugger).

JRE

Java Runtime Environment

Libraries + JVM for execution.

JVM

Java Virtual Machine

Converts bytecode → machine code.

Diagram:

JDK = JRE + Development Tools

JRE = JVM + Libraries

JVM = Execution Engine

 

  1. Explain OOP concepts in Java.
  • Encapsulation → Wrapping data/methods.
  • Inheritance → Extending functionality.
  • Polymorphism → One interface, many forms.
  • Abstraction → Hiding implementation.

3. Explain OOP concepts in Java

Code Example:

				
					abstract class Animal { abstract void sound(); }
class Dog extends Animal {
  void sound() { System.out.println("Bark"); }
}

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

    Operator

    Compares

    Example

    ==

    References (memory location)

    “abc” == “abc” → true

    .equals()

    Content

    “abc”.equals(new String(“abc”)) → true

     

    1. String vs StringBuilder vs StringBuffer

    Class

    Mutable

    Thread-Safe

    Performance

    String

    No

    Yes

    Slower

    StringBuilder

    Yes

    No

    Faster

    StringBuffer

    Yes

    Yes

    Slower (due to synchronization)

    StringBuilder sb = new StringBuilder(“Java”);

    sb.append(” Rocks”);

    System.out.println(sb);

     

    1. Explain Java Memory Model (Heap vs Stack)

    Diagram:

    Stack Memory       Heap Memory

    —————    ——————-

    – Local vars       – Objects

    – Method calls     – Class instances

    – Thread-specific  – Shared across threads

     

    1. What is Garbage Collection?

    Java automatically reclaims unused memory.

    • Generational GC: Young, Old, Permanent generations.

       

    • Algorithms: Mark-and-Sweep, Copying, Compacting.

       

7. What is Garbage Collection
				
					public class GCExample {
  public static void main(String[] args) {
    String s = new String("Hello");
    s = null; // eligible for GC
    System.gc();
  }
}

				
			
  1. Difference between final, finally, and finalize()

Term

Meaning

final

Keyword → constants, no inheritance, no override.

finally

Block in exception handling → always runs.

finalize()

Cleanup before GC (deprecated).

  1. Checked vs Unchecked Exceptions
  • Checked → Compile-time (IOException, SQLException).
  • Unchecked → Runtime (NullPointerException).

try {

  FileReader fr = new FileReader(“test.txt”); // checked

} catch (IOException e) { e.printStackTrace(); }

 

  1. HashMap vs Hashtable

Feature

HashMap

Hashtable

Thread-safe

No

Yes

Nulls

1 null key allowed

Not allowed

Performance

Faster

Slower

 

  1. Explain ConcurrentHashMap.
  • Thread-safe.
  • Divides map into segments → reduces contention.
  • Allows concurrent reads/writes.

ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();

map.put(1, “Java”);

 

  1. synchronized vs volatile

Keyword

Ensures

Use Case

synchronized

Mutual exclusion

Thread-safe methods

volatile

Visibility of changes

Flags, simple variables

 

  1. What are Streams in Java 8?

List<String> names = Arrays.asList(“Tom”,”Jerry”,”Mike”);

names.stream()

     .filter(s -> s.startsWith(“M”))

     .forEach(System.out::println);

 

  1. JVM, JIT, and ClassLoader
  • JVM → Executes bytecode.

  • JIT → Compiles hot code to native machine code.

  • ClassLoader → Dynamically loads classes.

Diagram:

Source → Bytecode → ClassLoader → JVM → Native Code

 

  1. Explain Escape Analysis.

JVM optimization: decides if object can be on stack instead of heap → reduces GC load.

15. Explain Escape Analysis

16. Implement Singleton in Java.

				
					public 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;
  }
}

				
			

17. Reverse a String

				
					String str = "Interview";
String reversed = new StringBuilder(str).reverse().toString();

				
			

18. Prime Number Program

				
					boolean isPrime(int n) {
  if (n <= 1) return false;
  for (int i = 2; i <= Math.sqrt(n); i++) {
    if (n % i == 0) return false;
  }
  return true;
}

				
			

19. Producer-Consumer Problem

				
					BlockingQueue<Integer> q = new ArrayBlockingQueue<>(5);

// Producer
new Thread(() -> {
  try { q.put(1); } catch(Exception e){}
}).start();

// Consumer
new Thread(() -> {
  try { System.out.println(q.take()); } catch(Exception e){}
}).start();

				
			
  1. Detect Deadlock in Java
  • Use ThreadMXBean from ManagementFactory.
  • Analyze thread dumps.

ThreadMXBean bean = ManagementFactory.getThreadMXBean();

long[] ids = bean.findDeadlockedThreads();

20. Detect Deadlock in Java

21. LRU Cache with LinkedHashMap

				
					class LRU<K,V> extends LinkedHashMap<K,V> {
  private int capacity;
  LRU(int cap){ super(cap,0.75f,true); this.capacity=cap; }
  protected boolean removeEldestEntry(Map.Entry<K,V> eldest){
    return size() > capacity;
  }
}

				
			
  1. How does Java support microservices?
  • Frameworks → Spring Boot, Micronaut, Quarkus.
  • Communication → REST, gRPC, Kafka.
  1. Securing Java Web Applications
  • Use Spring Security.
  • Avoid SQL injection with PreparedStatement.
  • Enable HTTPS and JWT authentication.
  1. New Features in Java 17
  • Sealed Classes.
  • Pattern Matching for Switch.
  • Strong Encapsulation.

sealed interface Shape permits Circle, Square {}

final class Circle implements Shape {}

  1. How to Optimize Java Performance?
  • Use efficient data structures.
  • Minimize object creation.
  • Use profilers (VisualVM, JConsole).
  • Apply caching.
  • Tune JVM parameters.

 

DSA, High & Low Level System Designs

Buy for 60% OFF
₹25,000.00 ₹9,999.00

Accelerate your Path to a Product based Career

Boost your career or get hired at top product-based companies by joining our expertly crafted courses. Gain practical skills and real-world knowledge to help you succeed.

Reach Out Now

If you have any queries, please fill out this form. We will surely reach out to you.

Contact Email

Reach us at the following email address.

arun@getsdeready.com

Phone Number

You can reach us by phone as well.

+91-97737 28034

Our Location

Rohini, Sector-3, Delhi-110085

WhatsApp Icon

Master Your Interviews with Our Free Roadmap!

Hi Instagram Fam!
Get a FREE Cheat Sheet on System Design.

Hi LinkedIn Fam!
Get a FREE Cheat Sheet on System Design

Loved Our YouTube Videos? Get a FREE Cheat Sheet on System Design.