🎯 Free Interview Preparation

Java Interview Questions & Answers

Complete Java interview preparation guide for freshers, experienced developers and architects.

50+Questions
Core JavaFundamentals
Java 8+Streams & Lambdas
ArchitectSystem Design

Java Junior Questions (1-10)

Question #1

What are the four pillars of OOP?

Java follows four OOP principles:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction
Question #2

Difference Between JDK, JRE and JVM

ComponentDescription
JDKDevelopment Kit
JRERuntime Environment
JVMJava Virtual Machine
Question #3

What is Method Overloading?

Same method name with different parameter lists.

class Calculator {

  int add(int a, int b) {
    return a + b;
  }

  int add(int a, int b, int c) {
    return a + b + c;
  }

}
Question #4

What is Method Overriding?

class Animal {

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

}

class Dog extends Animal {

  @Override
  void sound() {
    System.out.println("Bark");
  }

}
Question #5

Difference Between == and equals()

String a = new String("Java");
String b = new String("Java");

System.out.println(a == b);
System.out.println(a.equals(b));
Question #6

What is Constructor?

class Employee {

  Employee() {
    System.out.println("Created");
  }

}
Question #7

What is Inheritance?

class Vehicle {

  void start() {}

}

class Car extends Vehicle {

}
Question #8

What is Encapsulation?

class Employee {

  private String name;

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

}
Question #9

What is Abstraction?

abstract class Shape {

  abstract void draw();

}
Question #10

Abstract Class vs Interface

interface Payment {

  void pay();

}

class CreditCardPayment implements Payment {

  public void pay() {
    System.out.println("Paid");
  }

}
Mid-Level Question #11

Difference Between ArrayList and LinkedList

ArrayListLinkedList
Dynamic ArrayDoubly Linked List
Fast Random AccessSlow Random Access
Slow Insert/Delete in MiddleFast Insert/Delete
Less MemoryMore Memory
Follow-up: When would you choose LinkedList over ArrayList?
Mid-Level Question #12

How Does HashMap Work Internally?

HashMap stores data using key-value pairs.

Internal Steps

  1. Calculate hashCode()
  2. Find bucket index
  3. Store entry in bucket
  4. Handle collisions using LinkedList or Tree
Senior follow-up: What changed in Java 8 when collisions occur?
Mid-Level Question #13

Difference Between HashMap and Hashtable

HashMapHashtable
Not Thread SafeThread Safe
Allows Null KeysNo Null Keys
FasterSlower
Modern applications usually prefer ConcurrentHashMap.
Mid-Level Question #14

Difference Between HashSet and TreeSet

HashSetTreeSet
UnorderedSorted
O(1)O(log n)
Uses HashMapUses TreeMap
Set<Integer> numbers = new TreeSet<>();

numbers.add(10);

numbers.add(5);

numbers.add(20);
Mid-Level Question #15

Comparable vs Comparator

ComparableComparator
Natural SortingCustom Sorting
compareTo()compare()
Inside ClassSeparate Class
employees.sort(

  Comparator.comparing(Employee::getSalary)

);
Mid-Level Question #16

Difference Between String, StringBuilder and StringBuffer

TypeMutableThread Safe
StringNoYes
StringBuilderYesNo
StringBufferYesYes
Mid-Level Question #17

What is a Lambda Expression?

Lambda expressions provide a concise way to represent anonymous functions.

Introduced in Java 8.
Mid-Level Question #18

What is a Functional Interface?

An interface with exactly one abstract method.

@FunctionalInterface

interface Calculator {

  int add(int a, int b);

}

Common Functional Interfaces

  • Predicate
  • Function
  • Consumer
  • Supplier
Mid-Level Question #19

What is Stream API?

Stream API enables functional-style processing of collections.

List<Integer> numbers = List.of(1,2,3,4,5);

numbers.stream()

  .filter(n -> n % 2 == 0)

  .forEach(System.out::println);

Benefits

  • Readable Code
  • Functional Programming
  • Parallel Processing
Mid-Level Question #20

What is Optional in Java 8?

Optional helps avoid NullPointerException.

Common Methods

  • of()
  • ofNullable()
  • orElse()
  • orElseGet()
  • isPresent()
Follow-up: Why is Optional not recommended as an Entity field?
Senior Question #21

Explain JVM Memory Structure

JVM memory is divided into several areas used during program execution.

Memory AreaPurpose
HeapStores Objects
StackStores Method Calls & Local Variables
MetaspaceStores Class Metadata
PC RegisterCurrent Instruction
Native StackNative Method Calls
Very common senior Java interview question.
Senior Question #22

Difference Between Heap and Stack Memory

HeapStack
Stores ObjectsStores Local Variables
Shared Across ThreadsThread Specific
Managed by GCAutomatically Cleared
Employee employee = new Employee();

int age = 30;

employee object is stored in Heap while age is stored in Stack.

Senior Question #23

What is Garbage Collection?

Garbage Collection automatically removes objects that are no longer reachable.

Benefits

  • Automatic Memory Management
  • Reduces Memory Leaks
  • Improves Stability
Follow-up: Can we force Garbage Collection?

Expected Answer: System.gc() is only a request, not a guarantee.
Senior Question #24

What are Different Garbage Collectors?

GCUsage
Serial GCSmall Applications
Parallel GCHigh Throughput
G1 GCDefault Modern GC
ZGCLow Latency Systems
ShenandoahLarge Heap Applications
Senior Question #25

What is ClassLoader?

ClassLoader dynamically loads Java classes into memory.

Types

  • Bootstrap ClassLoader
  • Platform ClassLoader
  • Application ClassLoader
Follow-up: What is Parent Delegation Model?
Senior Question #26

What is Serialization?

Serialization converts an object into a byte stream.

public class Employee

implements Serializable {

  private String name;

}

Uses

  • Caching
  • Messaging Systems
  • File Storage
  • Network Transfer
Senior Question #27

What is Reflection API?

Reflection allows inspection and modification of classes at runtime.

Class<?> clazz = Employee.class;

Method[] methods = clazz.getMethods();

Common Framework Usage

  • Spring Framework
  • Hibernate
  • JUnit
Senior Question #28

Difference Between Thread and Process

ProcessThread
Independent Execution UnitLightweight Unit
Own MemoryShared Memory
ExpensiveCheaper
Senior Question #29

What is Synchronization?

Synchronization prevents multiple threads from accessing critical sections simultaneously.

public synchronized void deposit() {

  balance += 100;

}
Follow-up: What problems occur without synchronization?

Expected Answer: Race Conditions and Data Inconsistency.
Senior Question #30

What is ConcurrentHashMap?

ConcurrentHashMap provides thread-safe access without locking the entire map.

Advantages

  • Thread Safe
  • Better Performance Than Hashtable
  • High Concurrency Support
Very common Spring Boot and Microservices interview question.
Practical Question #31

Reverse a String

Write a program to reverse a string without using built-in reverse methods.

String input = "Java";

String reversed = new StringBuilder(input)
  .reverse()
  .toString();

System.out.println(reversed);
Follow-up: Reverse without using extra memory.
Practical Question #32

Check if a String is Palindrome

A palindrome reads the same forwards and backwards.

String input = "madam";

String reversed = new StringBuilder(input)
  .reverse()
  .toString();

System.out.println(
  input.equals(reversed)
);
Example: madam, racecar
Practical Question #33

Find Duplicate Characters in a String

String str = "java";

Map<Character, Integer> map = new HashMap<>();

for(char ch : str.toCharArray()) {

  map.put(
    ch,
    map.getOrDefault(ch, 0) + 1
  );

}

System.out.println(map);
Expected output: a → 3 v → 2
Practical Question #34

Find Missing Number in an Array

Array contains numbers 1 to N with one missing number.

int[] numbers = {1,2,3,5};

int expected = 5 * (5 + 1) / 2;

int actual = Arrays.stream(numbers).sum();

System.out.println(expected - actual);
Common Amazon, Microsoft and Oracle interview question.
Practical Question #35

Fibonacci Series

int a = 0;
int b = 1;

for(int i = 0; i < 10; i++) {

  System.out.print(a + " ");

  int temp = a + b;

  a = b;

  b = temp;

}
Follow-up: Recursive vs Iterative solution.
Practical Question #36

Find Duplicate Elements in an Array

int[] numbers = {1,2,3,2,4,1};

Set<Integer> unique = new HashSet<>();

for(int number : numbers){

  if(!unique.add(number)){

    System.out.println(number);

  }

}
Follow-up: Solve using Stream API.
Practical Question #37

Implement Singleton Pattern

Create a thread-safe Singleton.

public class Singleton {

  private static final Singleton INSTANCE =
      new Singleton();

  private Singleton() {}

  public static Singleton getInstance() {

    return INSTANCE;

  }

}
Frequently asked for experienced developers.
Practical Question #38

Create an Immutable Class

public final class Employee {

  private final String name;

  public Employee(String name) {

    this.name = name;

  }

  public String getName() {

    return name;

  }

}
Follow-up: Why is String immutable?
Practical Question #39

Sort Employees by Salary Using Stream API

employees.stream()

  .sorted(
    Comparator.comparing(
      Employee::getSalary
    )
  )

  .forEach(System.out::println);
Tests Stream API understanding.
Practical Question #40

Design an LRU Cache

Explain how you would implement an LRU Cache in Java.

Map<Integer, String> cache =
new LinkedHashMap<>(
  16,
  0.75f,
  true
);

Concepts Tested

  • HashMap
  • Doubly Linked List
  • Collections Framework
  • Design Skills
Very common product company interview question.
Architect Question #41

How Would You Design a High-Traffic E-Commerce Order System?

Key Components

  • Order Service
  • Inventory Service
  • Payment Service
  • Notification Service
  • Message Queue
  • Cache Layer

Expected Discussion

  • Database Transactions
  • Event Driven Architecture
  • Scalability
  • Failure Handling
Architect Question #42

How Would You Design a Notification System?

Channels

  • Email
  • SMS
  • Push Notifications
  • In-App Notifications

Architecture

Client
  ↓
Notification API
  ↓
Message Queue
  ↓
Email / SMS / Push Workers
Discuss retries, queues and failure recovery.
Architect Question #43

Synchronous vs Asynchronous Communication

SynchronousAsynchronous
REST APIKafka / RabbitMQ
Immediate ResponseEvent Driven
Tighter CouplingLooser Coupling
Architect Question #44

What is Event Driven Architecture?

Services communicate by publishing and consuming events.

Order Created Event

      ↓

Kafka Topic

      ↓

Inventory Service
Payment Service
Notification Service

Benefits

  • Loose Coupling
  • Scalability
  • Resilience
  • Independent Deployments
Architect Question #45

Explain Circuit Breaker Pattern

Prevents cascading failures when dependent services are unavailable.

States

  • Closed
  • Open
  • Half Open
Commonly implemented using Resilience4j.
Architect Question #46

How Would You Handle Distributed Transactions?

Approaches

  • Two Phase Commit (2PC)
  • Saga Pattern
  • Compensating Transactions
Modern microservices usually prefer Saga Pattern.
Architect Question #47

How Would You Design a Scalable Caching Strategy?

Cache Layers

  • Application Cache
  • Redis
  • CDN Cache
  • Database Cache

Cache Patterns

  • Cache Aside
  • Write Through
  • Write Behind
  • Read Through
Architect Question #48

How Would You Tune JVM Performance?

Areas To Investigate

  • Heap Size
  • GC Logs
  • Thread Dumps
  • Memory Leaks
  • CPU Profiling
-Xms2G
-Xmx4G

-XX:+UseG1GC

-XX:MaxGCPauseMillis=200
Strong candidates discuss G1GC and Heap Analysis.
Architect Question #49

Design a URL Shortener Like Bit.ly

Core Components

  • URL Generator
  • Database
  • Cache
  • Analytics
  • Redirect Service

Scalability Considerations

  • Read Replicas
  • Redis Cache
  • Rate Limiting
  • Load Balancing
Architect Question #50

Design a Real-Time Chat Application

Core Technologies

  • Spring Boot
  • WebSocket
  • Redis Pub/Sub
  • Kafka
  • MySQL/PostgreSQL
Client

   ↕

WebSocket Server

   ↕

Redis Pub/Sub

   ↕

Chat Service

   ↕

Database

Features

  • Presence Detection
  • Typing Indicators
  • Read Receipts
  • Message Persistence
  • Horizontal Scaling
This question evaluates system design, scalability and distributed systems knowledge.

Frequently Asked Questions

Are Java coding questions included?

Yes. Core Java, Collections, Streams, Multithreading and practical coding questions are covered.

Are Java 8 questions included?

Yes. Stream API, Lambda Expressions, Optional and Functional Interfaces are covered.

Does this cover JVM internals?

Yes. JVM, Heap, Stack, ClassLoader and Garbage Collection are covered.

Is this suitable for senior developers?

Yes. Senior and architect-level topics are included.