Section 1: Core Java Basics & Data Types
Q: Why is Java not 100% Object-Oriented?
A: Because it uses primitive data types (int, boolean, char, etc.) for performance reasons, which are not objects.
Q: What is the size of int, long, double, and float?
A: int is 4 bytes, long is 8 bytes, float is 4 bytes, and double is 8 bytes.
Q: What is a Marker Interface?
A: An interface with no methods or fields (e.g., Serializable, Cloneable). It signals the JVM or compiler to treat the object specifically.
Q: Can you override the main method?
A: No, you cannot override it because it is static. However, you can overload it (have multiple main methods with different args), but the JVM only runs the specific String[] signature.
Q: What is the default value of local variables?
A: Local variables do not have default values. They must be initialized before use, or the compiler will throw an error.
Q: What is the difference between System.out, System.err, and System.in?
A: out is the standard output stream (console), err is the standard error stream (usually red text), and in is the standard input stream (keyboard).
Q: What does the strictfp keyword do?
A: It ensures that floating-point calculations produce the exact same result on every platform (IEEE 754 standard) regardless of hardware precision.
Q: What is Type Casting? Difference between Widening vs. Narrowing?
A: Widening (Implicit) converts a smaller type to a larger type (int -> long). Narrowing (Explicit) converts a larger type to a smaller type (double -> int) and risks data loss.
Q: Can a source file contain more than one public class?
A: No. A .java file can have multiple classes, but only one can be public, and the file name must match the public class name.
Q: What is the purpose of the package keyword?
A: It groups related classes and interfaces to avoid naming conflicts and control access (encapsulation).
Section 2: String Handling
Q: Why is String immutable in Java?
A: For security (connection strings, passwords), synchronization (thread-safety), and caching (String Pool efficiency).
Q: What is the String Constant Pool?
A: A special memory area in the Heap where String literals are stored. If a string exists, the reference is returned instead of creating a new object.
Q: What happens if you create a String using new String("abc")?
A: Two objects are created: one in the Heap (normal memory) and one in the String Constant Pool (if "abc" isn't there already).
Q: How does substring() work internally?
A: It creates a new String object containing the specified range of characters from the original string.
Q: What is the difference between String.intern()?
A: It manually moves a String object created with new into the String Constant Pool (or returns the reference if it already exists).
Q: Is String thread-safe?
A: Yes, because it is immutable. Multiple threads can access the same String instance without risk of corruption.
Section 3: Object-Oriented Programming (Deep Dive)
Q: What is the difference between Aggregation and Composition?
A: Aggregation is a weak relationship (Driver and Car); the driver can exist without the car. Composition is a strong relationship (Heart and Body); the heart cannot exist if the body is destroyed.
Q: Can we override a private or static method?
A: No. Private methods are not visible to child classes. Static methods are bound to the class, not the instance, so redeclaring them is "Method Hiding," not overriding.
Q: What is Constructor Chaining?
A: Calling one constructor from another within the same class (using this()) or from the parent class (using super()).
Q: Can we declare a constructor as final?
A: No, constructors cannot be overridden, so marking them final is meaningless and causes a compile-time error.
Q: What is a Covariant Return Type?
A: Since Java 5, an overriding method can return a subtype of the return type declared in the parent method (e.g., Parent returns Number, Child returns Integer).
Q: What is an Initializer Block?
A: A block of code { ... } that runs every time an instance is created, before the constructor. static { ... } runs only once when the class is loaded.
Q: Can an Interface extend another Interface?
A: Yes, an interface can extend multiple other interfaces using the extends keyword.
Q: What is the difference between final, finally, and finalize?
A: final makes variables/methods/classes unchangeable. finally is a block in try-catch. finalize is a deprecated method called by GC before object deletion.
Section 4: Exception Handling
Q: What is the base class of all Exceptions?
A: Throwable. It has two main subclasses: Exception (recoverable) and Error (irrecoverable, e.g., StackOverflowError).
Q: Can we catch Error in a try-catch block?
A: Technically yes, but you shouldn't. Errors like OutOfMemoryError indicate serious JVM problems that an application cannot recover from.
Q: What happens if return is used in both try and finally?
A: The return value from the finally block will override the return value from the try block.
Q: Explain ClassCastException.
A: A runtime exception thrown when you try to cast an object to a subclass of which it is not an instance (e.g., casting a String to Integer).
Q: What is Exception Propagation?
A: If an exception is not caught in the current method, it drops down the call stack to the previous method until it is caught or reaches the main method.
Q: Can we throw null inside a try block?
A: No, throwing null explicitly (throw null;) results in a NullPointerException.
Section 5: Collections Framework (Essential)
Q: What is the difference between Collection and Collections?
A: Collection is the root interface (List, Set). Collections is a utility class containing static methods like sort(), reverse(), and synchronizedList().
Q: How does HashSet ensure uniqueness?
A: It uses HashMap internally. It calls hashCode() and equals() to check if the object already exists in the bucket.
Q: What is the difference between poll() and remove() in Queue?
A: poll() returns null if the queue is empty. remove() throws NoSuchElementException if the queue is empty.
Q: What is WeakHashMap?
A: A map where keys are "weakly reachable." If a key is no longer used elsewhere, the entry is automatically removed by Garbage Collection.
Q: What is the initial capacity and load factor of ArrayList and HashMap?
A: ArrayList: 10. HashMap: 16 (capacity) and 0.75 (load factor).
Q: Explain ConcurrentHashMap vs SynchronizedMap.
A: SynchronizedMap locks the entire map for any operation. ConcurrentHashMap locks only segments (buckets) allowing multiple threads to write simultaneously (higher performance).
Q: What is the IdentityHashMap?
A: A map that uses reference equality (==) instead of object equality (.equals()) for keys.
Q: How to make a collection Read-Only?
A: Use Collections.unmodifiableList(list), unmodifiableSet(set), etc. Any attempt to modify it throws UnsupportedOperationException.
Section 6: Multithreading & Concurrency
Q: What is the thread lifecycle (States)?
A: New, Runnable (Ready/Running), Blocked/Waiting, Timed Waiting, and Terminated.
Q: What is the difference between wait() and sleep()?
A: wait() releases the lock and waits for a notify. sleep() pauses execution but holds the lock. wait() is from Object, sleep() is from Thread.
Q: Can we start a thread twice?
A: No, calling start() on a thread that has already started throws IllegalThreadStateException.
Q: What is a Daemon Thread?
A: A low-priority background thread (like GC) that automatically terminates when all user threads finish execution.
Q: What is ThreadLocal?
A: A class that provides thread-local variables. Each thread accessing the variable has its own, independently initialized copy.
Q: What are Atomic classes (e.g., AtomicInteger)?
A: Classes that support lock-free thread-safe programming on single variables using CAS (Compare-And-Swap) hardware instructions.
Q: What is the Fork/Join framework?
A: Introduced in Java 7, it splits a large task into smaller subtasks (Fork), executes them in parallel, and combines results (Join). Used by parallelStream().
Q: What is a CountDownLatch?
A: A synchronizer that allows one or more threads to wait until a set of operations being performed in other threads completes (countdown reaches zero).
Q: What is a CyclicBarrier?
A: A synchronization point where all threads must wait until they all reach that barrier before any can proceed.
Section 7: Memory Management & Garbage Collection
Q: What is the Metaspace (Java 8+)?
A: It replaced the PermGen space. It stores class metadata and grows automatically in native memory, reducing OutOfMemoryError: PermGen space issues.
Q: What is the difference between Strong, Weak, Soft, and Phantom references?
A: Strong: Normal assignment (never GC'd). Soft: GC'd only if memory is low. Weak: GC'd eagerly. Phantom: Used to track when an object is removed from memory.
Q: Can we force Garbage Collection?
A: You can call System.gc(), but it is only a request/suggestion. The JVM is not obligated to run the GC immediately.
Q: What is "Stop-the-World" event?
A: A phase in GC where the JVM pauses all application threads to perform garbage collection. Tuning aims to minimize this time.
Q: What is the G1 Garbage Collector?
A: A server-style GC designed for multi-processor machines with large memory. It partitions the heap into regions and cleans the ones with the most garbage first.
Section 8: Modern Java (8, 11, 17, 21)
Q: What is the difference between map() and flatMap()?
A: map() transforms elements one-to-one (e.g., Stream> -> Stream
Q: What is a Method Reference (::)?
A: Shorthand syntax for a lambda expression that executes just one method (e.g., System.out::println instead of x -> System.out.println(x)).
Q: What are Default Methods in Interfaces?
A: Methods in an interface with a body (using default keyword). They allow adding new functionality to interfaces without breaking implementing classes.
Q: What is the Java Module System (JPMS) in Java 9?
A: It allows grouping packages into "Modules" to improve encapsulation and reduce the JRE size (Project Jigsaw).
Q: What is var in Java 10?
A: Local Variable Type Inference. It lets you declare variables without specifying the type (e.g., var list = new ArrayList
Q: What are Sealed Classes (Java 17)?
A: Classes that restrict which other classes may extend them (using sealed and permits), giving control over the inheritance hierarchy.
Q: What are Text Blocks (Java 15)?
A: Multi-line string literals enclosed in triple quotes """, eliminating the need for escape sequences like \n or concatenation.
Q: What is Pattern Matching for instanceof (Java 16)?
A: Avoids casting after a check. Instead of if (obj instanceof String) { String s = (String) obj; }, you write if (obj instanceof String s) { ... }.
Section 9: Input/Output (IO) & Serialization
Q: What is the difference between Byte Stream and Character Stream?
A: Byte Stream (InputStream) handles raw binary data (images, video) byte-by-byte. Character Stream (Reader) handles text data, managing character encoding automatically.
Q: What is serialVersionUID?
A: A unique ID for a Serializable class. If the class changes (fields added) and the ID doesn't match the serialized data, an InvalidClassException occurs.
Q: What is the transient keyword?
A: It marks a member variable so that it is not serialized. The value will be null/default when the object is deserialized.
Q: What is Externalizable interface?
A: It extends Serializable but gives you full control over the serialization logic via writeExternal() and readExternal() methods, often for performance.
Q: What is Java NIO (New IO)?
A: A non-blocking I/O API using Buffers and Channels. It allows one thread to manage multiple connections (Selectors), ideal for high-performance servers.
Section 10: JDBC & Databases
Q: What is the difference between Statement and PreparedStatement?
A: Statement compiles SQL every time (slow, vulnerable to SQL Injection). PreparedStatement is pre-compiled (fast, prevents SQL Injection using placeholders ?).
Q: What is the difference between execute(), executeQuery(), and executeUpdate()?
A: executeQuery: Returns ResultSet (Select). executeUpdate: Returns int (Insert/Update/Delete). execute: Returns boolean (general purpose).
Q: What is Connection Pooling?
A: Using a cache of database connections (e.g., HikariCP) so threads can reuse existing connections instead of paying the high cost of opening/closing them repeatedly.
Q: What is an ACID property in DB context?
A: Atomicity, Consistency, Isolation, Durability. It ensures database transactions are processed reliably.
Q: What is a Dirty Read?
A: When a transaction reads data that has been written by another transaction but not yet committed.
Section 11: Design Patterns
Q: What is the Factory Pattern?
A: A creational pattern where a Factory class decides which subclass to instantiate based on input logic, hiding creation complexity from the client.
Q: What is the Observer Pattern?
A: A behavioral pattern where an object (Subject) maintains a list of dependents (Observers) and notifies them automatically of any state changes (e.g., Event Listeners).
Q: What is the Decorator Pattern?
A: A structural pattern allowing you to add behavior to an individual object dynamically without affecting the behavior of other objects from the same class (e.g., Java IO streams).
Q: What is the Strategy Pattern?
A: Defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime (e.g., Collections.sort() using different Comparator strategies).
Q: What is the Builder Pattern?
A: A pattern used to construct complex objects step-by-step. It separates the construction of a complex object from its representation (e.g., Stream.builder()).
Section 12: Reflection & Classloaders
Q: What is Reflection in Java?
A: An API (java.lang.reflect) that allows the program to inspect and modify the behavior of classes, methods, and fields at runtime (even private ones).
Q: What are the risks of using Reflection?
A: It breaks encapsulation, has slower performance than direct calls, and can cause security issues or runtime errors that are hard to debug.
Q: What is a ClassLoader?
A: A subsystem of JVM that loads class files (.class) into memory. Types: Bootstrap (core libs), Extension/Platform, and Application/System.
Q: How does Class.forName() work?
A: It dynamically loads a class by its fully qualified name at runtime and executes its static block. Often used in loading JDBC drivers.
Section 13: Miscellaneous / Tricky Questions
Q: Can main method be declared private?
A: It compiles, but the JVM will not find it as an entry point and will throw a runtime error.
Q: What is the difference between StackOverflowError and OutOfMemoryError?
A: StackOverflow is due to deep/infinite recursion (Stack full). OutOfMemory is due to too many objects created (Heap full).
Q: Can you store a null key in HashMap? TreeMap?
A: HashMap: Yes (one null key). TreeMap: No, it throws NullPointerException because it needs to compare keys for sorting.
Q: What is the output of Math.min(Double.MIN_VALUE, 0.0d)?
A: It is 0.0d. Double.MIN_VALUE is the smallest positive non-zero number, not negative infinity.
Q: Can finally block NOT execute?
A: Only if System.exit() is called, the thread dies, or the OS kills the JVM process before the block is reached.
Q: What is the difference between process and thread?
A: A process is an independent execution unit with its own memory. A thread is a lightweight unit within a process, sharing memory space.
Q: What is the Cloneable interface? Deep vs Shallow Copy?
A: Shallow: Copies field values (references point to original objects). Deep: Copies the objects referenced as well (creating fully independent copies).
Q: What is Type Erasure?
A: The process where the compiler removes Generic type information (
Q: Why are arrays faster than ArrayList?
A: Arrays are a fixed-size, low-level data structure without the overhead of checking capacity, resizing, or wrapper objects.
Q: What is an Enum? Can it implement interfaces?
A: A special class representing a group of constants. Yes, Enums can implement interfaces but cannot extend other classes (they implicitly extend java.lang.Enum).
Q: What is Double Brace Initialization?
A: new ArrayList<>() {{ add("a"); }}. It creates an anonymous inner class. It is generally discouraged due to memory overhead and serialization issues.
Q: What is the native keyword?
A: It marks a method that is implemented in a language other than Java (usually C/C++) using JNI (Java Native Interface).
Q: Can we cast int to byte? What happens if int is larger?
A: Yes, explicitly. If the int is larger than byte (127), the bits are truncated (modulo arithmetic), causing data value changes (wrapping around).
Q: What is the difference between String literal and new String object?
A: Literal "A" goes to String Pool. new String("A") goes to Heap. ("A" == new String("A")) is false.
Q: Is Java Pass-by-Value or Pass-by-Reference?
A: Always Pass-by-Value. For objects, it passes the value of the reference (address), not the object itself.
Q: What is System.arraycopy()?
A: A native method to copy arrays. It is much faster than using a loop to copy elements manually.
Q: What is the difference between Enumeration and Iterator?
A: Enumeration is legacy (Vector/Stack) and read-only. Iterator is safer, allows removing elements (remove()), and works for all Collections.
Q: What is ListIterator?
A: An iterator for Lists that allows traversing in both directions (forward/backward) and modifying elements.
Q: What is the purpose of assert?
A: Used for debugging. If the condition is false, it throws an AssertionError. It is disabled by default in production (enable via -ea).
Q: What is Blank Final variable?
A: A final variable that is not initialized at declaration. It must be initialized in the constructor (instance) or static block (static).
Q: Why is char[] preferred over String for passwords?
A: String stays in the pool until GC runs (security risk). char[] can be explicitly wiped (set to 0s) immediately after use.
