Top Interview Questions
Java is one of the most popular, versatile, and powerful programming languages in the world. Developed by James Gosling and his team at Sun Microsystems in 1995, Java was designed with the philosophy of “Write Once, Run Anywhere” (WORA). This means that Java programs can run on any platform that has a compatible Java Virtual Machine (JVM), making Java a truly platform-independent language. Over the years, Java has evolved into a robust ecosystem used for building desktop applications, web applications, enterprise systems, mobile apps, cloud services, and more.
Java offers several features that make it reliable, secure, and developer-friendly:
Java code is compiled into bytecode, which is not specific to any operating system. This bytecode runs on the JVM, allowing Java programs to execute on Windows, Linux, macOS, and other platforms without modification.
Java is a fully object-oriented language, which means it is based on concepts like:
Classes
Objects
Inheritance
Polymorphism
Encapsulation
Abstraction
These concepts help developers build modular, reusable, and maintainable code.
Java syntax is similar to C and C++, but it removes complex features like pointers and multiple inheritance, making it simpler and less error-prone.
Java provides a secure execution environment through features like:
Bytecode verification
No explicit pointers
Security Manager
Sandbox execution
These features protect systems from malicious code.
Java emphasizes strong memory management, exception handling, and type checking. The automatic garbage collection feature helps prevent memory leaks.
Java supports multithreading, allowing multiple tasks to run concurrently. This improves performance and responsiveness, especially in applications like games, servers, and real-time systems.
Although Java is interpreted, the Just-In-Time (JIT) compiler improves performance by converting bytecode into native machine code at runtime.
Java follows a three-step execution model:
Java Source Code (.java)
Written by the programmer.
Compiler (javac)
Converts source code into bytecode (.class).
Java Virtual Machine (JVM)
Executes the bytecode on the target machine.
JDK (Java Development Kit): Used for developing Java applications.
JRE (Java Runtime Environment): Required to run Java applications.
JVM (Java Virtual Machine): Executes Java bytecode.
A class is a blueprint, and an object is an instance of that class.
Encapsulation binds data and methods together and restricts direct access using access modifiers like private, protected, and public.
Inheritance allows one class to acquire properties of another class using the extends keyword.
Polymorphism allows methods to perform different tasks based on context. It is achieved through:
Method Overloading
Method Overriding
Abstraction hides implementation details and shows only essential features using abstract classes and interfaces.
Java provides a rich set of built-in packages, including:
java.lang – Core classes (String, Math, Object)
java.util – Data structures and utilities
java.io – Input/Output operations
java.sql – Database connectivity
java.time – Date and time API
java.net – Networking support
These libraries reduce development time and improve code reliability.
Exception handling helps manage runtime errors gracefully. Java uses keywords such as:
try
catch
finally
throw
throws
By handling exceptions properly, Java applications become more robust and reliable.
Java handles memory automatically using Garbage Collection. Memory is divided into:
Heap – Stores objects
Stack – Stores method calls and local variables
Method Area – Stores class metadata
Garbage Collector automatically removes unused objects, improving application stability.
Java is widely used across various domains:
Tools like Eclipse, IntelliJ IDEA, and NetBeans are built using Java.
Java frameworks such as Spring, Spring Boot, Hibernate, and Struts are popular for building enterprise-grade web applications.
Java is the primary language for Android app development.
Java is extensively used in banking, insurance, and large-scale enterprise systems due to its scalability and security.
Technologies like Hadoop, Spark, and Kafka are built using Java.
Platform independent
Secure and robust
Large community support
Rich API and frameworks
Strong backward compatibility
High demand in the job market
Slower than some low-level languages like C/C++
Requires more memory
Verbose syntax compared to modern languages
Despite these limitations, Java remains a preferred choice for enterprise and large-scale systems.
Java continues to evolve with regular updates. Modern versions introduce features like:
Lambda expressions
Streams API
Modules
Improved garbage collectors
Enhanced performance
With its strong ecosystem and continuous innovation, Java remains future-proof.
Answer:
Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now owned by Oracle). Java is used to develop web applications, mobile apps (Android), desktop applications, enterprise systems, and embedded systems.
Key features of Java include:
Object-Oriented
Platform Independent
Secure
Robust
Multithreaded
Answer:
Java is platform-independent because it uses Bytecode.
When Java code is compiled, it is converted into bytecode (.class file). This bytecode can run on any system that has a Java Virtual Machine (JVM), regardless of the operating system.
Concept:
Write Once, Run Anywhere (WORA)
Answer:
JVM (Java Virtual Machine) is a virtual machine that:
Executes Java bytecode
Converts bytecode into machine code
Manages memory
Provides security
JVM is platform-dependent, but Java programs are platform-independent.
Answer:
Used by developers
Contains JRE + development tools (javac, debugger)
Used to run Java programs
Contains JVM + core libraries
Answer:
Simple
Object-Oriented
Platform Independent
Secure
Robust
Multithreading
High Performance
Distributed
Answer:
OOP is a programming approach based on objects, which contain data and methods.
Java supports OOP through:
Encapsulation
Inheritance
Polymorphism
Abstraction
Answer:
A class is a blueprint or template used to create objects. It defines properties (variables) and behaviors (methods).
Example:
class Student {
int id;
String name;
}
Answer:
An object is an instance of a class. It represents real-world entities.
Example:
Student s1 = new Student();
Answer:
Encapsulation is the process of wrapping data and methods together and protecting data using access modifiers.
Example:
class Employee {
private int salary;
public int getSalary() {
return salary;
}
}
Answer:
Inheritance allows one class to acquire properties of another class using the extends keyword.
Example:
class Animal {
void eat() {}
}
class Dog extends Animal {
void bark() {}
}
Answer:
Polymorphism means many forms.
It allows methods to behave differently based on the object.
Types:
Compile-time (Method Overloading)
Runtime (Method Overriding)
Answer:
When multiple methods have the same name but different parameters, it is method overloading.
Example:
int add(int a, int b) {}
int add(int a, int b, int c) {}
Answer:
When a subclass provides a specific implementation of a method already defined in its parent class.
Example:
class Parent {
void show() {}
}
class Child extends Parent {
void show() {}
}
Answer:
Abstraction hides implementation details and shows only functionality.
Achieved using:
Abstract classes
Interfaces
Answer:
An interface is a blueprint that contains abstract methods and constants.
Example:
interface Vehicle {
void run();
}
Answer:
An abstract class can have both abstract and non-abstract methods.
Example:
abstract class Shape {
abstract void draw();
}
Answer:
| Modifier | Scope |
|---|---|
| public | Everywhere |
| protected | Same package + subclass |
| default | Same package |
| private | Same class |
Answer:
A constructor is a special method used to initialize objects.
Rules:
Same name as class
No return type
Example:
class Test {
Test() {
System.out.println("Constructor called");
}
}
static keyword?Answer:
static belongs to the class, not objects.
Uses:
Static variables
Static methods
Static blocks
final keyword?Answer:
final variable → value cannot change
final method → cannot override
final class → cannot inherit
Answer:
An exception is an unexpected event that disrupts program execution.
Types:
Checked Exceptions
Unchecked Exceptions
Answer:
Used to handle exceptions and prevent program crash.
Example:
try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println(e);
}
Answer:
Multithreading allows multiple threads to run simultaneously, improving performance.
Answer:
Garbage Collection automatically removes unused objects from memory to free space.
Answer:
String is an immutable object used to store text.
Example:
String s = "Java";
== and .equals()?Answer:
== compares memory reference
.equals() compares content
Answer:
An array is a collection of similar data types stored in contiguous memory.
Example:
int[] a = {1, 2, 3};
Answer:
A package is a group of related classes and interfaces.
Example:
package com.company.project;
Answer:
Collection Framework provides classes like:
List
Set
Map
Queue
Answer:
List allows duplicates
Set does not allow duplicates
Answer:
JDK: Used for development (JRE + tools like compiler)
JRE: Used to run Java programs
JVM: Executes bytecode and manages memory
String, StringBuilder, and StringBuffer?Answer:
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread-safe | Yes | No | Yes |
| Performance | Slow | Fast | Medium |
Answer:
An immutable object cannot be changed after creation.
Example: String
Answer:
Wrapper classes convert primitive data types into objects.
Examples:
int → Integer
char → Character
Answer:
Autoboxing: Primitive → Wrapper
Unboxing: Wrapper → Primitive
Answer:
ArrayList is a resizable array implementation of List.
Answer:
| Array | ArrayList |
|---|---|
| Fixed size | Dynamic size |
| Can store primitives | Stores objects only |
| Faster | Slightly slower |
Answer:
LinkedList stores elements as nodes with pointers.
Answer:
ArrayList → faster access
LinkedList → faster insertion/deletion
Answer:
HashMap stores data in key-value pairs and allows one null key.
Answer:
HashMap is non-synchronized
Hashtable is synchronized
HashMap allows null keys; Hashtable doesn’t
Answer:
Set does not allow duplicate elements.
Answer:
HashSet uses hashing and does not maintain insertion order.
Answer:
HashSet → no order
TreeSet → sorted order
Answer:
Map stores data as key-value pairs.
Answer:
Iterator is used to traverse collections.
Answer:
Iterator is universal
Enumeration is legacy
Answer:
Handling runtime errors using try, catch, finally.
Answer:
Checked → compile-time
Unchecked → runtime
Answer:
Always executes whether exception occurs or not.
throw vs throws?Answer:
throw → explicitly throw exception
throws → declare exception
Answer:
Running multiple threads simultaneously.
Answer:
Thread → class
Runnable → interface
Answer:
Controls access to shared resources.
Answer:
Threads waiting for each other forever.
Answer:
Converting object into byte stream.
Answer:
Converting byte stream back to object.
transient keyword?Answer:
Prevents variable from serialization.
Answer:
Processes collections in functional style.
Answer:
Short syntax for functional interfaces.
Example:
(a, b) -> a + b
Answer:
JVM consists of:
Loads .class files into memory
Types: Bootstrap, Extension, Application
Heap: Stores objects
Stack: Stores method calls & local variables
Method Area / Metaspace: Class metadata
PC Register: Tracks current instruction
Native Method Stack
Interpreter
JIT Compiler
Garbage Collector
Answer:
GC automatically removes unused objects.
Young Generation (Eden, Survivor)
Old Generation
Metaspace
Serial GC
Parallel GC
CMS
G1 GC
== and .equals() (Real-time)Answer:
== compares reference
.equals() compares content
In HashMap, equals() and hashCode() must be consistent.
hashCode() and why is it important?Answer:
hashCode() returns an integer used in hashing collections like HashMap.
Contract:
If equals() is true, hashCode must be same
Same hashCode does not guarantee equals
Answer:
Uses array of buckets
Uses hash function
Uses linked list / red-black tree (Java 8+)
Time complexity:
Average: O(1)
Worst: O(log n)
Answer:
HashMap → Not thread-safe
ConcurrentHashMap → Thread-safe with segment locking
No null keys allowed in ConcurrentHashMap
Answer:
Fail-Fast → throws ConcurrentModificationException
Fail-Safe → works on copy
Example:
Fail-Fast → ArrayList
Fail-Safe → CopyOnWriteArrayList
Answer:
Initial capacity: 10
Growth formula: newCapacity = old * 1.5
Answer:
Comparable → natural ordering
Comparator → custom ordering
Answer:
Immutable objects cannot change state.
Benefits:
Thread-safe
Secure
Caching
Example: String
Answer:
Defines how threads interact through memory.
Key concepts:
Happens-before
Visibility
Atomicity
volatile and synchronizedAnswer:
volatile → visibility only
synchronized → visibility + atomicity
Answer:
Uses object monitor, mutex locks, and lock escalation.
Answer:
Deadlock occurs when threads wait for each other.
Prevention:
Lock ordering
Timeout
Avoid nested locks
Answer:
Executor manages thread lifecycle efficiently.
Answer:
Reuses threads to improve performance.
Runnable and CallableAnswer:
Runnable → no return
Callable → returns result and throws exception
Answer:
Future → result of async task
CompletableFuture → non-blocking async programming
Answer:
Processes collections functionally.
Example:
list.stream()
.filter(x -> x > 10)
.map(x -> x * 2)
.collect(Collectors.toList());
Answer:
map → one-to-one
flatMap → one-to-many flattening
Answer:
Avoids NullPointerException.
Answer:
Interface with single abstract method.
Example:
Runnable
Comparator
Supplier
Answer:
Custom exceptions
Global exception handlers
Logging
Meaningful error codes
Answer:
Checked → business logic
Unchecked → programming errors
Answer:
Automatically closes resources.
Answer:
Object → byte stream.
Problems:
Performance
Security
Versioning
transient and serialVersionUID?Answer:
transient → skip serialization
serialVersionUID → version control
Answer:
Immutability
Synchronization
Concurrent collections
Atomic classes
StringBuilder and StringBufferAnswer:
StringBuilder → faster, not thread-safe
StringBuffer → thread-safe
Answer:
Allows runtime inspection of classes.
Used in:
Spring
Hibernate
Answer:
Reflection
Dependency Injection
Proxies
AOP
Answer:
Shallow → reference copy
Deep → actual object copy
Answer:
Singleton
Factory
Builder
Observer
DAO
Answer:
Use double-checked locking.
Answer:
S – Single Responsibility
O – Open/Closed
L – Liskov Substitution
I – Interface Segregation
D – Dependency Inversion
Answer:
Efficient collections
Caching
JVM tuning
Thread pools
Answer:
Occurs when classes are not unloaded properly.
Answer:
Soft → cache
Weak → GC quickly
Phantom → cleanup
Answer:
Lightweight JVM
Faster startup
Reactive programming
Answer:
Memory leaks
Poor exception handling
Improper synchronization++++++++
ConcurrentHashMap work internally?Answer:
Uses bucket-level locking
Java 8 uses CAS (Compare-And-Swap) instead of segment locking
Allows concurrent read/write
No null keys or values
Answer:
To avoid ambiguity during concurrent operations and prevent NullPointerException.
Answer:
A low-level atomic operation used in multithreading to update values without locks.
Answer:
Used for parallel processing by dividing tasks into smaller subtasks.
submit() and execute() in ExecutorService?Answer:
execute() → no return
submit() → returns Future
Answer:
Stores thread-specific data.
Used in:
User sessions
Database connections
Logging
Answer:
Heap dump
JVisualVM
JProfiler
GC logs
Answer:
Heap space
Metaspace
GC overhead
Direct buffer memory
Answer:
PermGen (Java 7) → fixed size
Metaspace (Java 8+) → native memory
Answer:
Optimizing JVM parameters like heap size and GC algorithm.
Answer:
Parallel → multi-core processing
Sequential → single thread
Answer:
Small data sets
IO-heavy tasks
Shared mutable state
Answer:
Used by streams to split data for parallel processing.
Answer:
Intermediate operations execute only when terminal operation is called.
Answer:
Controls data flow in reactive systems.
Answer:
Imperative → step-by-step
Reactive → event-driven
Answer:
Non-blocking IO with buffers and channels.
Answer:
IO → blocking
NIO → non-blocking
CompletableFuture chaining?Answer:
Allows async task composition.
thenApply() and thenCompose()?Answer:
thenApply → transforms result
thenCompose → flattens async result
Answer:
Reuses database connections to improve performance.
Answer:
A fast JDBC connection pool.
Answer:
PreparedStatement
Input validation
ORM frameworks
Answer:
Statement → slow, unsafe
PreparedStatement → fast, secure
Answer:
Executes multiple SQL statements together.
Answer:
Ensures ACID properties.
Answer:
Optimistic → version-based
Pessimistic → database locks
Answer:
Pagination
Streaming
Batch processing
Indexing
Answer:
Maps Java objects to database tables.
Answer:
N+1 problem
LazyInitializationException
Answer:
Fetch joins
Batch fetching
Answer:
First-level → Session cache
Second-level → Application-wide
@Component, @Service, @Repository?Answer:
Used for stereotype classification in Spring.
Answer:
Aspect-Oriented Programming for cross-cutting concerns.
Answer:
Using proxies and annotations.
Answer:
Stateless web services using HTTP methods.
Answer:
PUT → full update
PATCH → partial update
Answer:
Multiple calls give same result.
Answer:
Authentication
Authorization
Encryption
Secure coding
Answer:
Memory leaks
Thread starvation
Slow GC