Skill Booster

Quick Reference for Interviews...

Top 100 Java Interview Question and Answers

Q1: Difference between JDK, JRE, and JVM basics

Core Java

JVM executes bytecode, JRE provides JVM + libraries, JDK includes JRE + compiler and tools.

Q2: Explain platform independence in Java basics

Core Java

Java compiles to bytecode, which runs on any JVM regardless of operating system.

Q3: Difference between == and equals() in Java basics

Core Java

== compares references, equals() compares values (if overridden properly).

Q4: What is the difference between String, StringBuilder, and StringBuffer? basics

Strings

String is immutable, StringBuilder is mutable and not synchronized, StringBuffer is mutable and synchronized.

Q5: Explain autoboxing and unboxing in Java basics

Wrapper Classes

Autoboxing converts primitives to wrapper objects, unboxing converts wrapper objects back to primitives.

Q6: Difference between primitive types and wrapper classes basics

Core Java

Primitives are basic data types, wrapper classes are objects that encapsulate primitives and provide methods.

Q7: What is type casting in Java? basics

Core Java

Type casting converts one data type into another. Implicit casting is automatic, explicit casting requires syntax.

Q8: Difference between final, finally, and finalize basics

Keywords

final is a keyword for constants, finally is a block for cleanup in try-catch, finalize() is a method called by GC.

Q9: Explain static keyword in Java basics

Core Java

Static members belong to the class rather than instances. Useful for utility methods and constants.

Q10: Difference between static and instance methods basics

Core Java

Static methods belong to the class and can be called without objects, instance methods require an object.

Q11: What is a constructor in Java? basics

Core Java

A constructor initializes objects. It has the same name as the class and no return type.

Q12: Difference between constructor and method basics

Core Java

Constructor initializes objects, methods define behavior. Constructors have no return type, methods do.

Q13: Explain method overloading vs overriding basics

Core Java

Overloading: same method name, different parameters. Overriding: subclass redefines parent method.

Q14: What is the difference between this and super keyword? basics

Core Java

this refers to current object, super refers to parent class object.

Q15: Explain access modifiers in Java basics

Core Java

public, protected, default, private — control visibility of classes, methods, and variables.

Q16: Difference between shallow copy and deep copy basics

Core Java

Shallow copy copies references, deep copy duplicates actual objects.

Q17: What is immutability in Java? basics

Strings

Immutable objects cannot be changed after creation. String is a prime example.

Q18: Difference between String pool and heap basics

Memory

String pool stores unique string literals, heap stores objects created with new keyword.

Q19: Explain garbage collection in Java basics

Memory Management

Automatic process that reclaims memory by removing unused objects. Triggered by JVM.

Q20: Difference between stack and heap memory basics

Memory Management

Stack stores method calls and local variables, heap stores objects and class instances.

Q21: What are the four pillars of OOP in Java? OOP

Object-Oriented Programming

Encapsulation, Inheritance, Polymorphism, and Abstraction are the four pillars of OOP in Java.

Q22: Difference between abstract class and interface OOP

Design

Abstract classes can have both abstract and concrete methods; interfaces (before Java 8) only had abstract methods. From Java 8 onward, interfaces can have default and static methods.

Q23: What is encapsulation in Java? OOP

Core Concept

Encapsulation is the practice of hiding internal details and exposing only necessary functionality through public methods. Achieved using private fields and getters/setters.

Q24: Explain inheritance in Java OOP

Core Concept

Inheritance allows a class to acquire properties and behaviors of another class using the extends keyword. Promotes code reuse.

Q25: What is polymorphism in Java? OOP

Core Concept

Polymorphism allows one interface to be used for different data types. Achieved through method overloading (compile-time) and overriding (runtime).

Q26: What is abstraction in Java? OOP

Core Concept

Abstraction hides implementation details and shows only essential features. Achieved using abstract classes and interfaces.

Q27: Difference between method overloading and overriding OOP

Core Concept

Overloading: same method name, different parameters (compile-time). Overriding: subclass redefines parent method (runtime).

Q28: Can a constructor be overridden? OOP

Core Concept

No, constructors cannot be overridden. They can be overloaded (multiple constructors with different parameters).

Q29: Difference between composition and inheritance OOP

Design

Inheritance is an “is-a” relationship, composition is a “has-a” relationship. Composition is often preferred for flexibility.

Q30: What is the difference between an inner class and a nested static class? OOP

Classes

Inner classes are tied to an instance of the outer class, nested static classes are not and can be instantiated without an outer class object.

Q31: What is multiple inheritance in Java? OOP

Inheritance

Java does not support multiple inheritance with classes to avoid ambiguity. It supports multiple inheritance through interfaces.

Q32: Difference between interface and marker interface OOP

Interfaces

Marker interfaces have no methods; they signal metadata to the JVM (e.g., Serializable, Cloneable).

Q33: Can an interface extend another interface? OOP

Interfaces

Yes, interfaces can extend other interfaces, allowing multiple inheritance of type.

Q34: Difference between abstract class and concrete class OOP

Classes

Abstract classes cannot be instantiated and may contain abstract methods. Concrete classes provide full implementation and can be instantiated.

Q35: What is the diamond problem in Java? OOP

Inheritance

Occurs when multiple inheritance leads to ambiguity. Java avoids this by not supporting multiple inheritance with classes.

Q36: Difference between super() and this() in constructors OOP

Constructors

super() calls the parent class constructor, this() calls another constructor in the same class.

Q37: Can we declare a class as final in Java? OOP

Classes

Yes, a final class cannot be extended. Example: String class is final.

Q38: What is the difference between instanceof and isAssignableFrom()? OOP

Type Checking

instanceof checks if an object is an instance of a class, isAssignableFrom() checks if a class is assignable from another class.

Q39: Explain method hiding in Java OOP

Methods

When a static method in a subclass has the same signature as one in the parent class, it hides the parent method instead of overriding it.

Q40: Difference between early binding and late binding OOP

Polymorphism

Early binding happens at compile-time (method overloading), late binding happens at runtime (method overriding).

Q41: Difference between HashMap and Hashtable collections

Collections Framework

HashMap is non-synchronized, allows one null key and multiple null values. Hashtable is synchronized, does not allow null keys or values, and is legacy.

Q42: Explain fail-fast vs fail-safe iterators collections

Concurrency

Fail-fast iterators throw ConcurrentModificationException if the collection is modified during iteration. Fail-safe iterators work on a copy, so they don’t throw exceptions.

Q43: Difference between ArrayList and LinkedList collections

Lists

ArrayList is backed by a dynamic array, better for random access. LinkedList is backed by a doubly linked list, better for frequent insertions/deletions.

Q44: Difference between HashSet and TreeSet collections

Sets

HashSet stores elements in a hash table, does not guarantee order. TreeSet stores elements in a Red-Black tree, maintains sorted order.

Q45: Difference between HashMap and ConcurrentHashMap collections

Concurrency

HashMap is not thread-safe. ConcurrentHashMap is thread-safe, uses segment locking for better concurrency, and does not allow null keys/values.

Q46: What is the difference between Comparable and Comparator? collections

Sorting

Comparable defines natural ordering via compareTo(), Comparator defines custom ordering via compare().

Q47: Explain difference between List, Set, and Map collections

Collections Framework

List: ordered, allows duplicates. Set: unordered, no duplicates. Map: key-value pairs, keys unique.

Q48: What is the difference between Iterator and ListIterator? collections

Iteration

Iterator can traverse forward only. ListIterator can traverse both forward and backward, and modify elements.

Q49: Explain difference between HashMap and TreeMap collections

Maps

HashMap stores entries in a hash table, no order guarantee. TreeMap stores entries in a Red-Black tree, maintains sorted order by keys.

Q50: What is the difference between WeakHashMap and HashMap? collections

Maps

WeakHashMap uses weak references for keys, allowing GC to reclaim them. HashMap uses strong references, keys are not garbage collected.

Q51: Explain difference between Enumeration and Iterator collections

Iteration

Enumeration is legacy, only supports read-only traversal. Iterator is modern, supports element removal during iteration.

Q52: What is the difference between Vector and ArrayList? collections

Lists

Vector is synchronized and legacy. ArrayList is not synchronized, preferred in modern applications.

Q53: Explain difference between LinkedHashMap and HashMap collections

Maps

LinkedHashMap maintains insertion order using a doubly linked list. HashMap does not guarantee order.

Q54: What is the difference between generic and non-generic collections? generics

Generics

Generic collections enforce type safety at compile-time. Non-generic collections store objects as type Object, requiring casting.

Q55: Explain type erasure in Java generics generics

Generics

Type erasure removes generic type information at runtime. Generics are enforced at compile-time, but erased during execution.

Q56: Difference between checked and unchecked exceptions exceptions

Error Handling

Checked exceptions must be declared in method signatures or handled with try-catch. Unchecked exceptions (RuntimeException and its subclasses) occur at runtime and don’t require explicit handling.

Q57: What is the difference between throw and throws in Java? exceptions

Error Handling

throw is used to explicitly throw an exception object. throws is used in method signatures to declare exceptions that a method may throw.

Q58: Explain try-catch-finally in Java exceptions

Error Handling

try encloses code that may throw exceptions, catch handles them, and finally executes cleanup code regardless of whether an exception occurred.

Q59: Difference between Error and Exception exceptions

Error Handling

Errors represent serious problems (like OutOfMemoryError) that applications should not try to handle. Exceptions represent conditions that applications can catch and handle.

Q60: What is the difference between throw and Throwable? exceptions

Error Handling

throw is a keyword used to throw exceptions. Throwable is the superclass of all errors and exceptions in Java.

Q61: Explain custom exceptions in Java exceptions

Error Handling

Custom exceptions are user-defined classes extending Exception or RuntimeException. They allow developers to represent application-specific error conditions.

Q62: Difference between final, finally, and finalize exceptions

Keywords

final is used for constants, finally is a block for cleanup in exception handling, and finalize() is a method called by the garbage collector before object destruction.

Q63: What is the difference between multiple catch blocks and multi-catch in Java? exceptions

Error Handling

Multiple catch blocks handle different exceptions separately. Multi-catch (Java 7+) allows handling multiple exceptions in a single catch block using the | operator.

Q64: Explain exception propagation in Java exceptions

Error Handling

Exception propagation is the process where an exception is passed up the call stack until it is caught or the program terminates.

Q65: Difference between try-with-resources and finally block exceptions

Error Handling

try-with-resources (Java 7+) automatically closes resources that implement AutoCloseable. finally block requires manual resource cleanup.

Q66: Difference between Thread and Runnable multithreading

Concurrency

Thread is a class that can be extended to create a new thread. Runnable is an interface that can be implemented by a class to define the run() method. Runnable is preferred for better resource sharing and flexibility.

Q67: Difference between process and thread multithreading

Concurrency

A process is an independent program with its own memory space. A thread is a lightweight unit of execution within a process that shares memory with other threads of the same process.

Q68: Explain synchronized keyword in Java multithreading

Concurrency

The synchronized keyword ensures that only one thread can access a block of code or method at a time, preventing race conditions.

Q69: Difference between synchronized method and synchronized block multithreading

Concurrency

Synchronized methods lock the entire method, while synchronized blocks allow finer control by locking only a specific section of code.

Q70: What is the difference between volatile and synchronized? multithreading

Concurrency

volatile ensures visibility of changes to variables across threads. synchronized ensures both visibility and atomicity by locking code blocks or methods.

Q71: Explain difference between wait(), notify(), and notifyAll() multithreading

Concurrency

wait() makes a thread wait until notified. notify() wakes up one waiting thread. notifyAll() wakes up all waiting threads on the same object monitor.

Q72: Difference between Callable and Runnable multithreading

Concurrency

Runnable’s run() method does not return a result or throw checked exceptions. Callable’s call() method returns a result and can throw checked exceptions.

Q73: What is the difference between ExecutorService and ForkJoinPool? multithreading

Concurrency

ExecutorService manages a pool of threads for tasks. ForkJoinPool is designed for divide-and-conquer tasks, splitting work into smaller subtasks and merging results.

Q74: Explain deadlock in Java multithreading

Concurrency

Deadlock occurs when two or more threads are waiting for each other’s resources, causing them to block indefinitely. It can be avoided by proper resource ordering and using tryLock.

Q75: Difference between concurrency and parallelism multithreading

Concurrency

Concurrency is about dealing with multiple tasks at once (interleaving execution). Parallelism is about executing multiple tasks simultaneously on different processors or cores.

Q76: Explain JVM memory model advanced

JVM Internals

The JVM memory model consists of Heap (objects), Stack (method frames), Method Area (class metadata), PC Register, and Native Method Stack. It ensures thread isolation and efficient memory management.

Q77: Difference between heap and stack memory in JVM advanced

Memory Management

Heap stores objects and is shared among threads. Stack stores method calls and local variables, and is thread-specific.

Q78: Explain garbage collection algorithms in Java advanced

Memory Management

Common algorithms include Mark-and-Sweep, Generational GC, G1 Garbage Collector. They reclaim memory by identifying and removing unreachable objects.

Q79: Difference between strong, weak, soft, and phantom references advanced

References

Strong references prevent GC. Weak references allow GC when no strong references exist. Soft references are cleared only under memory pressure. Phantom references are used for post-mortem cleanup.

Q80: Explain reflection in Java advanced

Advanced Features

Reflection allows inspection and modification of classes, methods, and fields at runtime. It is used in frameworks, IDEs, and testing tools.

Q81: Difference between Class.forName() and ClassLoader.loadClass() advanced

Class Loading

Class.forName() loads and initializes the class. ClassLoader.loadClass() loads the class but does not initialize it until explicitly used.

Q82: Explain difference between checked and unchecked exceptions in context of reflection advanced

Reflection

Reflection often throws checked exceptions like ClassNotFoundException, NoSuchMethodException, which must be handled. Runtime exceptions like IllegalAccessException may occur if access rules are violated.

Q83: What is the difference between serialization and deserialization? advanced

Persistence

Serialization converts an object into a byte stream for storage or transmission. Deserialization reconstructs the object from the byte stream.

Q84: Explain transient keyword in Java advanced

Persistence

Fields marked transient are excluded from serialization. Useful for sensitive or non-persistent data.

Q85: Difference between Serializable and Externalizable interfaces advanced

Persistence

Serializable provides default serialization. Externalizable requires implementing writeExternal() and readExternal() for custom serialization logic.

Q86: Difference between JDBC Statement and PreparedStatement enterprise

Database Access

Statement executes static SQL queries without parameters. PreparedStatement is precompiled, supports parameters, prevents SQL injection, and is faster for repeated queries.

Q87: Explain connection pooling in JDBC enterprise

Database Access

Connection pooling reuses database connections instead of creating new ones for each request, improving performance and resource utilization.

Q88: Difference between Hibernate and JDBC enterprise

ORM vs JDBC

JDBC is low-level API for direct SQL execution. Hibernate is an ORM framework that maps Java objects to database tables, reducing boilerplate code.

Q89: What is the difference between lazy loading and eager loading in Hibernate? enterprise

ORM

Lazy loading loads data on demand when accessed. Eager loading loads related data immediately with the parent entity.

Q90: Explain difference between Servlet and JSP enterprise

Web Technologies

Servlets are Java classes handling HTTP requests and responses. JSPs are HTML pages with embedded Java code, compiled into servlets for dynamic content.

Q91: Difference between doGet() and doPost() in Servlets enterprise

Web Technologies

doGet() is used for idempotent requests, parameters are appended to URL. doPost() is used for non-idempotent requests, parameters are sent in request body.

Q92: Explain MVC architecture in Java web applications enterprise

Web Architecture

MVC separates concerns: Model (business logic/data), View (UI), Controller (handles requests and updates model/view). Improves maintainability and scalability.

Q93: Difference between Spring and Spring Boot enterprise

Frameworks

Spring is a comprehensive framework for enterprise applications. Spring Boot simplifies configuration, provides embedded servers, and enables rapid development.

Q94: What is dependency injection in Spring? enterprise

Frameworks

Dependency Injection is a design pattern where Spring manages object creation and injects dependencies, improving testability and reducing coupling.

Q95: Explain difference between REST and SOAP web services enterprise

Web Services

REST uses lightweight HTTP methods (GET, POST, PUT, DELETE) and JSON/XML. SOAP uses XML-based protocol with strict standards, more overhead but built-in security.

Q96: Explain Singleton pattern in Java design

Design Patterns

The Singleton pattern ensures only one instance of a class exists in the JVM. It is implemented using a private constructor, a static instance, and a public static method to access the instance. Thread safety can be ensured with synchronized blocks or using enums.

Q97: What is the Factory pattern? design

Design Patterns

The Factory pattern provides an interface for creating objects but allows subclasses or factory classes to decide which class to instantiate. It promotes loose coupling and flexibility in object creation.

Q98: Explain Observer pattern in Java design

Design Patterns

The Observer pattern defines a one-to-many dependency between objects. When one object (subject) changes state, all dependent objects (observers) are notified automatically. Commonly used in event handling and messaging systems.

Q99: What is the Builder pattern? design

Design Patterns

The Builder pattern separates the construction of a complex object from its representation. It allows step-by-step object creation and improves readability, especially when dealing with many optional parameters.

Q100: Explain Dependency Injection in Java best-practices

Best Practices

Dependency Injection is a design principle where objects are provided their dependencies externally rather than creating them internally. It improves testability, reduces coupling, and is widely used in frameworks like Spring.