Interview
Core Java — Interview Questions (200+)
Format: detailed questions have Short / Detailed / Example; the rapid-fire section packs many more.
Detailed Questions
1. What is the difference between JDK, JRE, and JVM?
- Short: JVM runs bytecode; JRE = JVM + libraries; JDK = JRE + dev tools.
- Detailed: The JVM is the abstract machine that loads/verifies/executes
.classbytecode and manages memory/GC. The JRE packages the JVM with the standard class library so you can run programs. The JDK adds development tools (javac,jar,javadoc,jshell) so you can build programs. - Example:
javac App.java(JDK) producesApp.class, whichjava App(JRE/JVM) executes.
2. Why is Java "platform independent"?
- Short: Compiles to bytecode that any JVM can run.
- Detailed: Source compiles once to platform-neutral bytecode; each OS has its own JVM that interprets/JITs that bytecode. "Write once, run anywhere." The JVM itself is platform-dependent.
- Example: The same
App.classruns on Windows, Linux, and macOS JVMs.
3. `==` vs `.equals()`?
- Short:
==compares references/primitives;equalscompares logical value. - Detailed: For objects
==checks identity (same reference).equalsis overridable for value equality; if you overrideequalsyou must overridehashCode. Watch the Integer cache (-128..127). - Example:
new String("a") == new String("a")isfalse, but.equalsistrue.
4. What is the contract between `equals` and `hashCode`?
- Short: Equal objects must have equal hash codes.
- Detailed: If
a.equals(b)thena.hashCode() == b.hashCode(). The reverse is not required (collisions allowed). Breaking this corrupts hash-based collections (HashMap,HashSet). - Example: Use
Objects.hash(field1, field2)consistently with the fields used inequals.
5. Why are Strings immutable?
- Short: Safety, caching (string pool), thread-safety, and hashcode caching.
- Detailed: Immutability allows the string pool to share literals safely, makes Strings safe to use as map keys, enables hashcode caching, and avoids accidental mutation across references (security: file paths, class loading).
- Example:
s.toUpperCase()returns a new String;sis unchanged.
6. `String` vs `StringBuilder` vs `StringBuffer`?
- Short: String immutable; StringBuilder mutable (not thread-safe, fast); StringBuffer mutable (synchronized).
- Detailed: Concatenating Strings in a loop creates many objects (O(n²)). Use
StringBuilderfor single-threaded building,StringBufferonly if multiple threads mutate the same buffer. - Example:
StringBuilder sb=new StringBuilder(); for(...) sb.append(x);
7. What is autoboxing and a common pitfall?
- Short: Auto conversion primitive↔wrapper; pitfall is the Integer cache and NPE on unboxing null.
- Detailed:
Integer i = 5;boxes;int j = i;unboxes. Unboxing anullInteger throws NPE.==on Integers compares references except cached -128..127. - Example:
Integer a=1000,b=1000; a==bisfalse; usea.equals(b).
8. Checked vs unchecked exceptions?
- Short: Checked must be declared/handled; unchecked (RuntimeException) need not be.
- Detailed: Checked = recoverable conditions the caller should handle (
IOException). Unchecked = programming errors (NullPointerException,IllegalArgumentException).Error(e.g.OutOfMemoryError) should not be caught. - Example:
void read() throws IOException(checked);list.get(99)throws uncheckedIndexOutOfBounds.
8b. final vs finally vs finalize?
- Short:
final= constant/non-overridable;finally= always-run block;finalize= deprecated GC hook. - Detailed:
finalapplies to variables (constant), methods (no override), classes (no subclass).finallyruns after try/catch for cleanup.finalize()was called before GC—unreliable and removed/deprecated; use try-with-resources orCleaner. - Example:
try{...}finally{conn.close();}
9. Overloading vs overriding?
- Short: Overloading = same name, different params (compile-time); overriding = redefine inherited method (runtime).
- Detailed: Overloading is resolved statically by argument types. Overriding uses dynamic dispatch on the runtime type; signature must match;
@Overriderecommended; can't reduce visibility or broaden checked exceptions. - Example:
add(int,int)vsadd(double,double)(overload);Dog.sound()overridesAnimal.sound().
10. Abstract class vs interface?
- Short: Abstract class = partial impl + state, single inheritance; interface = contract, multiple inheritance, default methods.
- Detailed: Use an abstract class for shared state/behavior and an "is-a" with common base. Use interfaces for capabilities and to allow a type to play many roles. Since Java 8 interfaces have
default/static; since 9privatemethods. - Example:
abstract class Payment(shared amount) vsinterface Comparable.
11. Can you override a static method?
- Short: No — static methods are hidden, not overridden.
- Detailed: Statics belong to the class, resolved at compile time by reference type (method hiding). There's no dynamic dispatch.
- Example: A subclass
static m()hides the parent's; calling via parent reference uses parent's.
12. What does `static` mean and when does a static block run?
- Short: Belongs to the class; static block runs once at class init.
- Detailed: Static fields/methods are shared; no instance needed. Static initializer blocks run once when the class is first actively used, top-to-bottom.
- Example: Caches/constants;
static { LOOKUP = build(); }
13. What is the `this` and `super` keyword?
- Short:
this= current object;super= parent. - Detailed:
this.fielddisambiguates;this(...)calls another constructor.super.method()calls parent's version;super(...)calls parent constructor (must be first statement). - Example:
Dog(String n){ super(n); }
14. What is a marker interface?
- Short: An empty interface signaling a capability.
- Detailed: Has no methods; used by JVM/libraries to tag classes (
Serializable,Cloneable). Annotations are the modern alternative. - Example:
class X implements Serializable {}
15. What is the difference between `throw` and `throws`?
- Short:
throwraises an exception;throwsdeclares possible exceptions. - Detailed:
throw new X()actually throws;throws Xin a method signature declares that callers must handle/declare it. - Example:
void f() throws IOException { throw new IOException(); }
16. What are records and when to use them?
- Short: Immutable data carriers (Java 16+).
- Detailed: Generate constructor, accessors,
equals/hashCode/toString. Implicitly final; components final. Use for DTOs, value objects, tuple-like returns. Add compact constructors to validate. - Example:
record Point(int x,int y){}
17. What are sealed classes?
- Short: Restrict which types can extend/implement (Java 17+).
- Detailed:
sealed ... permits A, B. Subtypes must befinal,sealed, ornon-sealed. Enables exhaustive switches withoutdefault. Pairs with records for algebraic data types. - Example:
sealed interface Shape permits Circle, Square {}
18. What is the difference between `==` for floating point and `BigDecimal`?
- Short: Floating point is inexact; use
BigDecimalfor money. - Detailed:
0.1 + 0.2 != 0.3due to binary representation.BigDecimalgives exact decimal arithmetic (with scale/rounding). Never usedoublefor currency. - Example:
new BigDecimal("0.1").add(new BigDecimal("0.2"))is exactly 0.3.
19. Pass-by-value or pass-by-reference?
- Short: Always pass-by-value (for objects, the reference value is copied).
- Detailed: You can mutate the object a parameter points to, but reassigning the parameter doesn't affect the caller's variable.
- Example: Passing a
Listlets youaddto it; settinglist = new ...inside the method doesn't change the caller.
20. What is the diamond problem and how does Java handle default methods?
- Short: Conflict when two interfaces provide the same default method.
- Detailed: Java forces the implementing class to override and can call
Interface.super.method()to disambiguate. - Example:
class C implements A,B { public void m(){ A.super.m(); } }
21. What is the difference between `Comparable` and `Comparator`?
- Short:
Comparable= natural order (compareTo);Comparator= external/custom order. - Detailed: Implement
Comparablefor the class's default ordering. UseComparatorfor multiple/alternate orderings without modifying the class; compose withcomparing().thenComparing().reversed(). - Example:
list.sort(Comparator.comparing(Person::age).thenComparing(Person::name));
22. What is the `transient` keyword?
- Short: Excludes a field from serialization.
- Detailed: A
transientfield is skipped during default serialization (restored as default value). Use for sensitive or derived data. - Example:
private transient String password;
23. What is a varargs method and a caveat?
- Short:
Type...accepts 0+ args as an array; only one, last. - Detailed: Internally an array; ambiguity with overloads and heap-pollution warnings with generics (
@SafeVarargs). - Example:
int sum(int... xs)
24. What's the difference between `Iterator` and `ListIterator` and fail-fast?
- Short:
ListIteratoris bidirectional and list-only; fail-fast iterators throwConcurrentModificationException. - Detailed: Modifying a collection during iteration (except via the iterator) triggers
ConcurrentModificationExceptionin fail-fast collections. Concurrent collections are fail-safe. - Example: Use
it.remove()to delete during iteration safely.
25. What is the Object class and its key methods?
- Short: Root of all classes;
equals,hashCode,toString,getClass,clone,wait/notify. - Detailed: Every class implicitly extends
Object. Overrideequals/hashCode/toStringfor value semantics and debugging. - Example:
@Override public String toString(){...}
Rapid-Fire (Q → A)
- Is Java pure OOP? → No; it has primitives (not objects).
- Default value of
int? → 0. Ofboolean? → false. Of object reference? → null. - Can
mainbe overloaded? → Yes, but JVM only callsString[]version. - Can
mainbefinal? → Yes. - Can we run a class without
main? → Not as an app entry (since static-init-only is gone). - Size of
int? → 32-bit. Ofchar? → 16-bit. - Is
charsigned? → No, it's unsigned (0..65535). - What is unicode in Java? →
charis a UTF-16 code unit. - Can a constructor be private? → Yes (singletons, factories).
- Can a constructor be
final/static/abstract? → No. - Does a constructor return a value? → No (not even void).
- What is constructor chaining? →
this()/super()calls among constructors. - Default constructor provided when? → When you declare no constructor.
- Can interfaces have constructors? → No.
- Can interfaces have fields? → Yes, implicitly
public static final. - Can interface methods be private? → Yes (Java 9+, for helper default methods).
- Multiple inheritance of classes? → No; of interfaces/type → yes.
- What is method hiding? → Static method "override" resolved by type.
- Covariant return types? → Override can return a subtype.
- Can you reduce visibility when overriding? → No.
- Can overriding method throw broader checked exceptions? → No.
- What is the
instanceofoperator? → Tests runtime type; supports pattern binding. - What is autounboxing NPE? → Unboxing a null wrapper throws NPE.
- Ternary operator? →
cond ? a : b. - Labeled break? →
break label;exits an outer loop. - Difference
>>and>>>? → Arithmetic (sign-extending) vs logical (zero-fill) right shift. - What is the comma in for? → Multiple init/update expressions.
- Enhanced for limitation? → No index, can't modify the collection structurally.
- Is
switchfall-through? → Classic:falls through; arrow->does not. switchon what types? → int, char, byte, short, enum, String, and patterns (21).- What is a text block? →
"""..."""multi-line string (Java 15+). - What is
var? → Local variable type inference (Java 10+). - Where can't
varbe used? → Fields, params, return types, without initializer. - Is
vardynamic typing? → No, still static. - What is
finalvariable? → Assign once. - Blank final? →
finalfield assigned in constructor. - Effectively final? → Not reassigned; usable in lambdas.
- What is shadowing? → Local var hiding a field/outer var.
- Static vs instance initializer? →
static {}runs at class load;{}per instance before constructor. - Order of init? → static fields/blocks (once) → instance fields/blocks → constructor.
- Can we overload by return type? → No.
- Can we overload main? → Yes.
- Are arrays objects? → Yes; have
lengthfield. - Array covariance issue? →
Object[] = String[]allowsArrayStoreExceptionat runtime. - Jagged array? → Array of arrays with different lengths.
- Default array values? → Zero/false/null per type.
- Clone an array? →
arr.clone()(shallow). - Deep vs shallow copy? → Shallow copies references; deep copies nested objects.
Arrays.asListgotcha? → Fixed-size, backed by array;addthrows.List.ofgotcha? → Immutable, no nulls.- What is autoboxing cost? → Object allocation in tight loops.
- NaN comparisons? →
NaN != NaN; useDouble.isNaN. - Integer overflow behavior? → Wraps silently; use
Math.addExactto detect. Math.floorModvs%? → floorMod handles negatives to give non-negative result.- What is the string pool? → Cache of interned string literals.
intern()? → Returns the pooled instance of a string.equalson StringBuilder? → Identity (not overridden); comparetoString().- Convert int→String? →
String.valueOf(i)/Integer.toString(i). - String→int? →
Integer.parseInt(s). compareToreturns? → Negative/zero/positive.- Immutability benefits? → Thread safety, caching, safe sharing.
- How to make a class immutable? → final class, final private fields, no setters, defensive copies.
- Defensive copy? → Copy mutable inputs/outputs to protect invariants.
- What is encapsulation? → Hiding state behind methods.
- What is abstraction? → Exposing essentials, hiding details.
- Inheritance vs composition? → Prefer composition ("has-a") for flexibility.
- Liskov substitution? → Subtypes must be substitutable for base types.
- What is a POJO? → Plain Old Java Object, no framework requirements.
- What is a JavaBean? → POJO with no-arg ctor, getters/setters, Serializable.
clone()requirements? → ImplementCloneable, overrideclone.- Why is
Cloneableflawed? → Noclonemethod in interface; shallow by default. - Alternative to clone? → Copy constructor / static factory.
- Singleton pitfalls? → Reflection, serialization, classloaders; enum solves them.
- What is serialization? → Converting object to byte stream.
serialVersionUID? → Version id for serialization compatibility.- Externalizable vs Serializable? → Externalizable gives full manual control.
- What's an inner class? → Non-static nested class; holds outer reference.
- Static nested class? → No outer instance reference.
- Local class? → Class defined in a method.
- Anonymous class? → Unnamed one-off implementation.
- Lambda vs anonymous class? → Lambda has no own
this, targets functional interface. - Functional interface? → One abstract method (
@FunctionalInterface). - Method reference kinds? → static, instance-of-particular, instance-of-arbitrary, constructor.
- What is
Optional? → Container for value-or-absent; avoid null. - Optional misuse? → As fields/params; calling
get()blindly. - What is an enum? → Type-safe constant set; each a singleton.
- Enum methods? →
values(),valueOf(),ordinal(),name(). - EnumSet/EnumMap? → High-performance enum-keyed collections.
- Annotation? → Metadata; processed at compile/runtime.
- Meta-annotations? →
@Retention,@Target,@Inherited,@Documented. - Retention policies? → SOURCE, CLASS, RUNTIME.
- Reflection? → Inspect/modify classes at runtime.
- Reflection downsides? → Slow, breaks encapsulation, no compile checks.
- What is generics erasure? → Generic type info removed at runtime.
- Raw type? → Generic used without type param (legacy).
- Bounded type? →
<T extends Number>. - Wildcard? →
<?>,<? extends T>,<? super T>. - PECS? → Producer Extends, Consumer Super.
- Can you create
new T[]? → No (erasure); use reflection/Object[]. - What is a NPE and how to avoid? → Null dereference; use Optional, Objects.requireNonNull, null checks.
Objects.requireNonNull? → Throws NPE early with a message.Objects.equals? → Null-safe equals.Objects.hash? → Convenience hashCode.- try-with-resources requires? →
AutoCloseable. - Multi-catch syntax? →
catch (A | B e). - Can finally override return? → Yes (avoid
returnin finally). - Suppressed exceptions? → From try-with-resources close;
getSuppressed(). - Custom exception? → Extend Exception/RuntimeException.
- Exception chaining? →
new X("msg", cause). - Difference Error vs Exception? → Error = serious JVM issues; don't catch.
- StackOverflowError cause? → Deep/infinite recursion.
- OutOfMemoryError causes? → Heap exhaustion, leaks, metaspace.
- What is a memory leak in Java? → Reachable-but-unused refs (static collections, listeners, ThreadLocal).
- ThreadLocal use/risk? → Per-thread state; leaks in pools if not removed.
- What is immutability vs thread-safety? → Immutable objects are inherently thread-safe.
- Difference
lengthvslength()vssize()? → array.length, String.length(), Collection.size(). - Difference array vs ArrayList? → Fixed vs dynamic; primitives vs objects.
- Autobox in collections? → Collections store objects, so primitives box.
- What is a wrapper class? → Object form of a primitive.
- Parse vs valueOf? → parseInt→primitive; valueOf→wrapper (cached).
- Char to int? → Implicit widening or
Character.getNumericValue. - String formatting? →
String.format/"%d".formatted(x). - printf? →
System.out.printf(...). - StringBuilder capacity? → Internal buffer; grows as needed.
- Reverse a string? →
new StringBuilder(s).reverse(). - Split with regex? →
s.split(",")uses regex. - Difference replace vs replaceAll? → replace=literal, replaceAll=regex.
- Immutable collections? →
List.of,Collections.unmodifiableList. - What is boxing identity trap? →
==on boxed values beyond cache range. - Why prefer interfaces in declarations? → Program to abstraction (
List l = new ArrayList()). - Difference
extendsvsimplements? → Class inherits class vs implements interface. - Can a class extend multiple classes? → No.
- Can interface extend multiple interfaces? → Yes.
- Default method conflict resolution? → Override +
I.super.m(). - Static methods in interfaces? → Allowed (Java 8+), not inherited.
- What is upcasting/downcasting? → To supertype (implicit) / to subtype (explicit, risky).
- ClassCastException? → Invalid downcast.
- instanceof before cast? → Safe-guards downcasts.
- What is polymorphism benefit? → Code to base type, behavior varies.
- Dynamic dispatch? → Runtime method selection by object type.
- Static binding? → Compile-time (private/static/final/overloaded).
- Constructor inheritance? → Constructors are not inherited.
- Can abstract class have constructor? → Yes (called via subclass).
- Can abstract method be private/static/final? → No (must be overridable).
- Interface vs abstract for evolution? → Default methods evolve interfaces safely.
- What is the
assertkeyword? → Debug-time invariant; disabled by default (-ea). - Why not use assert for arg validation? → It can be disabled; use exceptions.
- What is
native? → Method implemented in native code (JNI). - What is
strictfp? → Portable floating-point (mostly obsolete). - What is
volatile? → Visibility guarantee across threads. - What is
synchronized? → Mutual exclusion + visibility via monitor.
More rapid-fire: 04 Concurrency · 03 Collections · 06 Streams
- What makes good Java code? → Clear naming, small methods, immutability, proper exceptions, tests, and idiomatic APIs.