HomeInterview QuestionsJava Interview Questions
Free Study Guide · 2025

Top 50 Java Interview Questions & Answers (2025)

Java is the backbone of enterprise software in India — asked in every TCS, Infosys, Wipro, Cognizant campus drive and product company interview. These questions cover everything from core OOP to Spring Boot, multithreading, and JVM internals.

20 questions
Detailed answers
100% free
1What are the four pillars of Object-Oriented Programming?
Encapsulation (binding data and methods together, hiding internals via access modifiers), Inheritance (a child class acquires properties of a parent class), Polymorphism (one interface, many implementations — method overloading and overriding), and Abstraction (hiding complexity, exposing only essential features via abstract classes or interfaces).
2What is the difference between an abstract class and an interface?
An abstract class can have implemented methods, constructors, instance variables, and can extend only one class. An interface (prior to Java 8) only had abstract methods; since Java 8 it can have default and static methods but no instance state. A class can implement multiple interfaces but extend only one class. Use interfaces for capability contracts, abstract classes for shared base implementations.
3What is the difference between == and .equals() in Java?
== compares object references (memory addresses) for objects, and values for primitives. .equals() compares the logical content of objects — it's overridden in String, Integer, and other classes to compare values. Always use .equals() to compare String content; == on String literals may appear to work due to the String pool but is unreliable for non-literal strings.
4What is the Java Memory Model? Explain heap and stack.
The stack stores method call frames, local primitives, and object references — each thread has its own stack. The heap stores all objects and class instances — shared across threads. The Metaspace (replaced PermGen in Java 8) stores class metadata. Understanding this distinction is key for diagnosing OutOfMemoryErrors and threading issues.
5What is garbage collection in Java?
Java's garbage collector automatically reclaims memory from objects that are no longer reachable (no live references). The JVM uses generational GC: most objects are young (created and quickly collected in Eden space), survivors move to older generations. Modern collectors include G1 (default since Java 9), ZGC, and Shenandoah — all designed for low-pause-time collection.
6What is the difference between ArrayList and LinkedList?
ArrayList is backed by a dynamic array — O(1) random access but O(n) insertion/deletion in the middle. LinkedList is a doubly-linked list — O(1) insertion/deletion at ends but O(n) random access. Use ArrayList for most use cases (better cache locality); use LinkedList only when frequent insertions/deletions at both ends outweigh the overhead of pointer traversal.
7What is the difference between HashMap and Hashtable?
HashMap is not synchronised (not thread-safe), allows one null key and multiple null values, and is faster. Hashtable is synchronised (thread-safe via method-level locking), allows no null keys or values, and is slower. In modern code, use ConcurrentHashMap for thread-safe maps — it uses segment-level locking for much better concurrent performance than Hashtable.
8What is the difference between checked and unchecked exceptions?
Checked exceptions (IOException, SQLException) are verified at compile time — you must either catch them or declare them with throws. Unchecked exceptions (RuntimeException subclasses like NullPointerException, ArrayIndexOutOfBoundsException) are not checked at compile time. Checked exceptions model recoverable conditions; unchecked model programming errors.
9What is multithreading and how do you create a thread in Java?
Multithreading allows concurrent execution of multiple threads within a process, sharing heap memory. You can create threads by: (1) extending Thread class and overriding run(), (2) implementing Runnable and passing it to Thread, or (3) implementing Callable with an ExecutorService for tasks that return values. The modern approach is using ExecutorService and thread pools rather than managing threads directly.
10What is synchronisation in Java and why is it needed?
Synchronisation prevents race conditions by ensuring only one thread at a time executes a critical section. Use the synchronized keyword on methods or blocks. volatile ensures visibility of variable changes across threads but doesn't ensure atomicity. Java's java.util.concurrent package provides higher-level tools: ReentrantLock, Semaphore, CountDownLatch, and atomic classes.
11What are Java Streams? (Java 8+)
Streams provide a functional-style API for processing sequences of elements. They support operations like filter(), map(), reduce(), sorted(), collect(), and forEach(). Streams are lazy — intermediate operations are only executed when a terminal operation is called. They support parallel processing via parallelStream() to leverage multi-core CPUs automatically.
12What are lambda expressions in Java?
Lambdas are anonymous functions introduced in Java 8 that implement a functional interface (an interface with exactly one abstract method). Syntax: (params) -> expression or (params) -> { body }. They eliminate boilerplate anonymous inner classes. Combined with Streams and method references, they enable a functional programming style in Java.
13What is the Optional class in Java 8?
Optional<T> is a container that may or may not hold a non-null value, designed to replace null returns and reduce NullPointerExceptions. Key methods: Optional.of(value), Optional.empty(), .isPresent(), .get(), .orElse(default), .orElseGet(supplier), .map(), and .filter(). It forces callers to explicitly handle the absent case rather than blindly dereferencing.
14What is the difference between String, StringBuilder, and StringBuffer?
String is immutable — every modification creates a new object, making repeated concatenation in loops O(n²). StringBuilder is mutable and not thread-safe — the right choice for string construction in single-threaded code. StringBuffer is mutable and thread-safe (synchronized methods) but slower. Always use StringBuilder in loops; use + for simple one-line concatenation (the compiler optimises it anyway).
15What is Spring Boot and why is it used?
Spring Boot is an opinionated framework that auto-configures a Spring application based on the dependencies on the classpath, eliminating most boilerplate XML and Java configuration. It embeds Tomcat/Jetty, provides production-ready actuator endpoints, and lets you create standalone REST APIs with minimal setup. It's the dominant choice for building Java microservices and REST APIs in India.
16What is Dependency Injection (DI) and Inversion of Control (IoC)?
IoC is the principle of inverting control of object creation from the class to an external container. DI is how IoC is implemented — dependencies are injected into a class (via constructor, setter, or field) rather than the class creating them. Spring's IoC container manages bean lifecycle and wiring. DI makes code testable, modular, and loosely coupled.
17What is the difference between @Component, @Service, @Repository, and @Controller?
All four are Spring stereotype annotations that declare a class as a Spring-managed bean. @Component is generic. @Service annotates the service layer (business logic). @Repository annotates the data access layer and adds exception translation. @Controller/@RestController annotates web layer classes handling HTTP requests. They are semantically different but functionally equivalent for component scanning.
18What is JPA and Hibernate?
JPA (Java Persistence API) is a specification for ORM (Object-Relational Mapping) in Java. Hibernate is the most popular implementation of JPA. Hibernate maps Java objects to database tables, translates method calls into SQL, manages transactions, and provides a cache. Spring Data JPA further simplifies this with repository interfaces that generate queries from method names.
19What is the SOLID principle?
SOLID is five object-oriented design principles: Single Responsibility (a class should have one reason to change), Open/Closed (open for extension, closed for modification), Liskov Substitution (subclasses should be substitutable for their parent), Interface Segregation (don't force clients to implement unused methods), Dependency Inversion (depend on abstractions, not concretions). Following SOLID leads to maintainable, testable code.
20What is the difference between final, finally, and finalize()?
final is a keyword: applied to a variable (constant), method (cannot be overridden), or class (cannot be extended). finally is a block in try-catch that always executes, used for cleanup (closing resources — though try-with-resources is preferred). finalize() is a deprecated method called by the GC before an object is collected — avoid relying on it for resource cleanup.
Level up your prep
Get company-specific questions for your interview
Upload your resume → get questions tailored to Google, Amazon, TCS, and 50+ companies.
Try AI Interview Prep →
© 2025 CareerLens · Home · Interview Questions · Pricing