Java Interview Questions & Answers
Complete Java interview preparation guide for freshers, experienced developers and architects.
Java Junior Questions (1-10)
What are the four pillars of OOP?
Java follows four OOP principles:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
Difference Between JDK, JRE and JVM
| Component | Description |
|---|---|
| JDK | Development Kit |
| JRE | Runtime Environment |
| JVM | Java Virtual Machine |
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;
}
}What is Method Overriding?
class Animal {
void sound() {
System.out.println("Animal");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}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));What is Constructor?
class Employee {
Employee() {
System.out.println("Created");
}
}What is Inheritance?
class Vehicle {
void start() {}
}
class Car extends Vehicle {
}What is Encapsulation?
class Employee {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}What is Abstraction?
abstract class Shape {
abstract void draw();
}Abstract Class vs Interface
interface Payment {
void pay();
}
class CreditCardPayment implements Payment {
public void pay() {
System.out.println("Paid");
}
}Difference Between ArrayList and LinkedList
| ArrayList | LinkedList |
|---|---|
| Dynamic Array | Doubly Linked List |
| Fast Random Access | Slow Random Access |
| Slow Insert/Delete in Middle | Fast Insert/Delete |
| Less Memory | More Memory |
How Does HashMap Work Internally?
HashMap stores data using key-value pairs.
Internal Steps
- Calculate hashCode()
- Find bucket index
- Store entry in bucket
- Handle collisions using LinkedList or Tree
Difference Between HashMap and Hashtable
| HashMap | Hashtable |
|---|---|
| Not Thread Safe | Thread Safe |
| Allows Null Keys | No Null Keys |
| Faster | Slower |
Difference Between HashSet and TreeSet
| HashSet | TreeSet |
|---|---|
| Unordered | Sorted |
| O(1) | O(log n) |
| Uses HashMap | Uses TreeMap |
Set<Integer> numbers = new TreeSet<>();
numbers.add(10);
numbers.add(5);
numbers.add(20);Comparable vs Comparator
| Comparable | Comparator |
|---|---|
| Natural Sorting | Custom Sorting |
| compareTo() | compare() |
| Inside Class | Separate Class |
employees.sort(
Comparator.comparing(Employee::getSalary)
);Difference Between String, StringBuilder and StringBuffer
| Type | Mutable | Thread Safe |
|---|---|---|
| String | No | Yes |
| StringBuilder | Yes | No |
| StringBuffer | Yes | Yes |
What is a Lambda Expression?
Lambda expressions provide a concise way to represent anonymous functions.
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
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
What is Optional in Java 8?
Optional helps avoid NullPointerException.
Common Methods
- of()
- ofNullable()
- orElse()
- orElseGet()
- isPresent()
Explain JVM Memory Structure
JVM memory is divided into several areas used during program execution.
| Memory Area | Purpose |
|---|---|
| Heap | Stores Objects |
| Stack | Stores Method Calls & Local Variables |
| Metaspace | Stores Class Metadata |
| PC Register | Current Instruction |
| Native Stack | Native Method Calls |
Difference Between Heap and Stack Memory
| Heap | Stack |
|---|---|
| Stores Objects | Stores Local Variables |
| Shared Across Threads | Thread Specific |
| Managed by GC | Automatically Cleared |
Employee employee = new Employee();
int age = 30;employee object is stored in Heap while age is stored in Stack.
What is Garbage Collection?
Garbage Collection automatically removes objects that are no longer reachable.
Benefits
- Automatic Memory Management
- Reduces Memory Leaks
- Improves Stability
Expected Answer: System.gc() is only a request, not a guarantee.
What are Different Garbage Collectors?
| GC | Usage |
|---|---|
| Serial GC | Small Applications |
| Parallel GC | High Throughput |
| G1 GC | Default Modern GC |
| ZGC | Low Latency Systems |
| Shenandoah | Large Heap Applications |
What is ClassLoader?
ClassLoader dynamically loads Java classes into memory.
Types
- Bootstrap ClassLoader
- Platform ClassLoader
- Application ClassLoader
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
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
Difference Between Thread and Process
| Process | Thread |
|---|---|
| Independent Execution Unit | Lightweight Unit |
| Own Memory | Shared Memory |
| Expensive | Cheaper |
What is Synchronization?
Synchronization prevents multiple threads from accessing critical sections simultaneously.
public synchronized void deposit() {
balance += 100;
}Expected Answer: Race Conditions and Data Inconsistency.
What is ConcurrentHashMap?
ConcurrentHashMap provides thread-safe access without locking the entire map.
Advantages
- Thread Safe
- Better Performance Than Hashtable
- High Concurrency Support
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);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)
);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);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);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;
}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);
}
}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;
}
}Create an Immutable Class
public final class Employee {
private final String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}Sort Employees by Salary Using Stream API
employees.stream()
.sorted(
Comparator.comparing(
Employee::getSalary
)
)
.forEach(System.out::println);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
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
How Would You Design a Notification System?
Channels
- SMS
- Push Notifications
- In-App Notifications
Architecture
Client
↓
Notification API
↓
Message Queue
↓
Email / SMS / Push WorkersSynchronous vs Asynchronous Communication
| Synchronous | Asynchronous |
|---|---|
| REST API | Kafka / RabbitMQ |
| Immediate Response | Event Driven |
| Tighter Coupling | Looser Coupling |
What is Event Driven Architecture?
Services communicate by publishing and consuming events.
Order Created Event
↓
Kafka Topic
↓
Inventory Service
Payment Service
Notification ServiceBenefits
- Loose Coupling
- Scalability
- Resilience
- Independent Deployments
Explain Circuit Breaker Pattern
Prevents cascading failures when dependent services are unavailable.
States
- Closed
- Open
- Half Open
How Would You Handle Distributed Transactions?
Approaches
- Two Phase Commit (2PC)
- Saga Pattern
- Compensating Transactions
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
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=200Design 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
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
↕
DatabaseFeatures
- Presence Detection
- Typing Indicators
- Read Receipts
- Message Persistence
- Horizontal Scaling
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.
