Java Interview Questions
26 questions with detailed answers
Question:
What is Java and what are its main features?
Answer:
Java is a high-level, object-oriented programming language developed by Sun Microsystems (now Oracle). Main features include: Platform Independence (Write Once, Run Anywhere), Object-Oriented Programming, Automatic Memory Management (Garbage Collection), Multithreading support, Security features, Robustness, and Rich API.
Question:
What is the difference between JDK, JRE, and JVM?
Answer:
JVM (Java Virtual Machine): Runtime environment that executes Java bytecode. JRE (Java Runtime Environment): Includes JVM + libraries needed to run Java applications. JDK (Java Development Kit): Includes JRE + development tools like compiler (javac), debugger, etc.
Question:
What is method overloading in Java?
Answer:
Method overloading is a feature that allows a class to have multiple methods with the same name but different parameters (different number of parameters, different types of parameters, or different order of parameters). The compiler determines which method to call based on the method signature.
Question:
Explain the concept of inheritance in Java with an example.
Answer:
Inheritance is a mechanism where a new class (child/subclass) acquires properties and methods of an existing class (parent/superclass). It promotes code reusability. Example:\nclass Animal { void eat() { System.out.println("Eating"); } }\nclass Dog extends Animal { void bark() { System.out.println("Barking"); } }\nDog can use both eat() and bark() methods.
Question:
What is the difference between abstract class and interface?
Answer:
Abstract Class: Can have both abstract and concrete methods, can have constructors, can have instance variables, supports single inheritance. Interface: All methods are abstract by default (before Java 8), cannot have constructors, all variables are public static final, supports multiple inheritance.
Question:
What is the purpose of the final keyword in Java?
Answer:
The final keyword can be used with: Variables (makes them constants), Methods (prevents method overriding), Classes (prevents inheritance, like String class). Final variables must be initialized and cannot be reassigned.
Question:
Explain exception handling in Java.
Answer:
Exception handling uses try-catch-finally blocks to handle runtime errors gracefully. Try block contains code that might throw exception, catch block handles specific exceptions, finally block executes regardless of exception occurrence. Java has checked exceptions (must be handled) and unchecked exceptions (runtime exceptions).
Question:
What is the difference between Comparable and Comparator interfaces?
Answer:
Comparable: Used for natural ordering, implemented by the class itself, has compareTo() method, provides single sorting sequence. Comparator: Used for custom ordering, implemented separately, has compare() method, provides multiple sorting sequences. Example: String implements Comparable for alphabetical sorting, but you can create Comparator for length-based sorting.
Question:
Explain the concept of multithreading in Java and how to create threads.
Answer:
Multithreading allows concurrent execution of multiple threads. Threads can be created by: 1) Extending Thread class and overriding run() method, 2) Implementing Runnable interface and implementing run() method. Thread synchronization can be achieved using synchronized keyword, locks, or concurrent collections.
Question:
What is the difference between HashMap and ConcurrentHashMap?
Answer:
HashMap is not thread-safe and can cause infinite loops in concurrent environments. ConcurrentHashMap is thread-safe, uses segment-based locking (before Java 8) or CAS operations (Java 8+), allows concurrent reads and limited concurrent writes, and provides better performance in multithreaded applications.
Question:
Explain Java Memory Model and Garbage Collection.
Answer:
Java Memory Model consists of Heap (Young Generation: Eden, S0, S1; Old Generation), Method Area/Metaspace, Stack, PC Register, and Native Method Stack. Garbage Collection automatically manages memory by removing unreferenced objects. Common GC algorithms include Serial, Parallel, G1, and ZGC.
Question:
What are Java 8 features and explain Stream API.
Answer:
Java 8 features: Lambda expressions, Stream API, Method references, Default methods in interfaces, Optional class, New Date/Time API. Stream API provides functional-style operations on collections, supports operations like filter, map, reduce, collect, and enables parallel processing.
Question:
Write a Java program to implement Singleton design pattern.
Answer:
public class Singleton {\n private static Singleton instance;\n private Singleton() {}\n \n public static synchronized Singleton getInstance() {\n if (instance == null) {\n instance = new Singleton();\n }\n return instance;\n }\n}\n\n// Thread-safe lazy initialization:\npublic class Singleton {\n private static volatile Singleton instance;\n private Singleton() {}\n \n public static Singleton getInstance() {\n if (instance == null) {\n synchronized (Singleton.class) {\n if (instance == null) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n}
Question:
Explain deadlock in Java and how to prevent it.
Answer:
Deadlock occurs when two or more threads are blocked forever, waiting for each other. Prevention methods: 1) Avoid nested locks, 2) Avoid unnecessary locks, 3) Use timeout with tryLock(), 4) Lock ordering (always acquire locks in same order), 5) Use concurrent collections. Example: Thread1 locks A then B, Thread2 locks B then A - this can cause deadlock.
Question:
Explain the difference between fail-fast and fail-safe iterators in Java.
Answer:
Fail-fast iterators throw ConcurrentModificationException if collection is modified during iteration (ArrayList, HashMap iterators). Fail-safe iterators work on copy of collection and do not throw exception (ConcurrentHashMap, CopyOnWriteArrayList iterators). Fail-fast detects concurrent modification immediately, fail-safe may not reflect latest changes.
Question:
What is the difference between ClassNotFoundException and NoClassDefFoundError?
Answer:
ClassNotFoundException: Checked exception thrown when trying to load class using Class.forName(), ClassLoader.loadClass() but class not found in classpath. NoClassDefFoundError: Error thrown when class was available at compile time but not available at runtime, or when static initialization fails.
Question:
Explain Java NIO and its advantages over traditional IO.
Answer:
NIO (New IO/Non-blocking IO): Uses channels and buffers instead of streams, supports non-blocking operations, provides selectors for multiplexing. Advantages: Better performance for high-volume applications, single thread can handle multiple connections, memory-mapped files, direct buffers. Traditional IO is blocking and thread-per-connection model.
Question:
What is the volatile keyword and when should you use it?
Answer:
Volatile ensures visibility of variable changes across threads and prevents instruction reordering. When one thread modifies volatile variable, change is immediately visible to other threads. Use cases: flags for thread termination, double-checked locking, publisher-subscriber scenarios. Does not provide atomicity for compound operations.
Question:
Explain the concept of weak references in Java.
Answer:
Weak references allow referencing an object without preventing garbage collection. Types: WeakReference (basic weak reference), SoftReference (cleared when memory is low), PhantomReference (for cleanup actions). Used in caches, listeners, avoiding memory leaks. WeakHashMap uses weak references for keys.
Question:
Write a thread-safe Singleton using enum.
Answer:
public enum Singleton {\n INSTANCE;\n \n public void doSomething() {\n System.out.println("Doing something...");\n }\n}\n\n// Usage: Singleton.INSTANCE.doSomething();\n// This is thread-safe by default and prevents reflection attacks.
Question:
Implement a custom thread pool executor.
Answer:
public class CustomThreadPool {\n private final BlockingQueue taskQueue;\n private final List workers;\n private volatile boolean isShutdown;\n \n public CustomThreadPool(int poolSize) {\n taskQueue = new LinkedBlockingQueue<>();\n workers = new ArrayList<>();\n for (int i = 0; i < poolSize; i++) {\n Worker worker = new Worker();\n workers.add(worker);\n worker.start();\n }\n }\n \n public void execute(Runnable task) {\n if (!isShutdown) {\n taskQueue.offer(task);\n }\n }\n \n private class Worker extends Thread {\n public void run() {\n while (!isShutdown) {\n try {\n Runnable task = taskQueue.take();\n task.run();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n }\n }\n}
Question:
What are the different types of class loaders in Java?
Answer:
1. Bootstrap ClassLoader: Loads core Java classes (rt.jar), written in native code. 2. Extension ClassLoader: Loads classes from extension directories (ext folder). 3. Application ClassLoader: Loads classes from classpath. 4. Custom ClassLoaders: User-defined for specific requirements. Follows parent delegation model.
Question:
Explain JIT compilation in Java.
Answer:
JIT (Just-In-Time) compiler compiles bytecode to native machine code at runtime for frequently executed code (hot spots). HotSpot JVM uses profiling to identify hot methods, then compiles them for better performance. C1 compiler for quick compilation, C2 compiler for aggressive optimization. Tiered compilation uses both.
Question:
Implement Observer pattern in Java.
Answer:
interface Observer {\n void update(String message);\n}\n\nclass Subject {\n private List observers = new ArrayList<>();\n \n public void addObserver(Observer observer) {\n observers.add(observer);\n }\n \n public void removeObserver(Observer observer) {\n observers.remove(observer);\n }\n \n public void notifyObservers(String message) {\n for (Observer observer : observers) {\n observer.update(message);\n }\n }\n}\n\nclass ConcreteObserver implements Observer {\n private String name;\n \n public ConcreteObserver(String name) {\n this.name = name;\n }\n \n public void update(String message) {\n System.out.println(name + " received: " + message);\n }\n}
Question:
What is the difference between CountDownLatch and CyclicBarrier?
Answer:
CountDownLatch: One-time use, threads wait for countdown to reach zero, cannot be reset. Use case: waiting for multiple tasks to complete. CyclicBarrier: Reusable, threads wait for each other at barrier point, can be reset. Use case: parallel processing where threads need to synchronize at checkpoints.
Question:
Explain the Fork/Join framework in Java.
Answer:
Fork/Join framework is designed for parallel processing using divide-and-conquer approach. ForkJoinPool manages worker threads, ForkJoinTask represents computations. RecursiveTask returns result, RecursiveAction does not. Work-stealing algorithm: idle threads steal tasks from busy threads queues for load balancing.