InterviewForge AI Logo
Core Java · Full stack bridgeLast updated Mar 27, 202661+ cards in this pack

Core Java Interview Questions & Answers

Sections aligned with popular Java interview guides (freshers → full stack + MCQ), written in our own words and laid out in InterviewForge AI’s emerald “study grid” UI.

Work through **Java for freshers**, **intermediate** core APIs, **experienced-level** JVM and concurrency, **coding problems**, **tricky** behaviors, **scenarios**, **memory**, **Java 11**, **full-stack Java**, then **MCQs**. Expand any card for a tight interview answer. Optional code samples appear where they help more than prose.

1Java Interview Questions for Freshers

Platform basics, memory model at a high level, OOP, constructors, exceptions, static, and GC fundamentals.

Language & platform

Why is Java described as platform independent?
The `javac` compiler turns source into bytecode (`.class` files). Bytecode is not tied to one CPU/OS: any compliant JVM on that machine loads it and either interprets or JIT-compiles it to native code. The same artifact can ship everywhere a JVM exists—as long as you stay within supported APIs and versions.
JVM bytecode
Why is Java not considered a “pure” object-oriented language?
Java still has primitive types (`int`, `double`, `boolean`, …) that are not objects. Everything else is rooted in classes, but those primitives break a strict “everything is an object” rule. Wrappers (`Integer`, etc.) bridge the gap when you need objects.
OOP primitives
What is the difference between stack and heap memory in Java?
Each thread gets a stack of frames: local variables and call state live there with automatic cleanup when methods return. Objects and arrays typically live on the heap; references from the stack point into the heap. The heap is shared across threads and is reclaimed by garbage collection.
memory JVM
How does Java differ from C++ at a high level?
Java targets the JVM (portable bytecode) while typical C++ compiles to native machine code per platform. Java hides manual memory management behind GC; C++ expects explicit ownership discipline. Java allows single inheritance for classes but multiple interface implementation; C++ supports multiple implementation inheritance. Java avoids raw pointers in user code.
comparison
Why doesn’t Java expose pointers like C or C++?
Safety and simplicity: raw pointer arithmetic enables crashes and security issues. Java uses opaque references you cannot increment arithmetically. The runtime and GC reason about the object graph reliably. That trade-off removes some low-level control but cuts an entire class of defects.
memory security

OOP, variables, and control flow

What is the difference between an instance variable and a local variable?
Instance fields belong to an object (one slot per instance), live for the object’s lifetime, and get default values on allocation. Local variables live in a stack frame, exist only inside their block/method, and must be definitely assigned before use—no implicit default in ordinary locals.
variables OOP
What default values do instance and class fields get?
Numeric primitives default to 0, `boolean` to false, `char` to `\u0000`, and reference types to null. Local variables have no default: reading before assignment is a compile-time error unless the compiler can prove assignment on all paths.
defaults
What is encapsulation?
Bundling data + behavior in a class and exposing a minimal, stable API (often via methods) so internal representation can change without breaking callers. `private` fields with intentional accessors preserve invariants.
OOP
What does a JIT compiler do in the JVM?
After bytecode loads, hot methods can be compiled to native code so later invocations run faster than pure interpretation. The JIT records profiling data (branch frequency, types) and may deoptimize/recompile as behavior changes. It is a performance layer on top of the interpreter—not a replacement for `javac`.
JIT performance
Compare `==` and `.equals()` for reference types.
`==` compares reference identity unless used on primitives (numeric/boolean equality). `.equals()` expresses logical equality and is overridden on types like `String`, `Integer`, and your domain classes. For strings, prefer `Objects.equals(a,b)` when nulls are possible.
String equality

Methods, exceptions, static, GC basics

How do you write an intentional infinite loop in Java?
Common idioms: `while (true) { }`, `for (;;) { }`, or `do { } while (true);`. Production code still needs break, return, or interruption strategy to exit—prefer bounded loops in servers unless you truly mean an event pump.
control-flow
What is constructor overloading?
Multiple constructors in one class with different parameter lists. The compiler picks the best match. Constructors can chain with `this(...)` and must invoke `super(...)` as the first statement if another constructor isn’t delegated via `this`.
constructors
Can the `main` method be overloaded?
Yes—`public static void main(String[] args)` is only the entry the JVM searches for. Other `main` overloads are legal but ignored for startup unless your code calls into them explicitly.
JVM
Why is `main` static?
The JVM starts execution without an instance. A static entry point can run from the class alone. If `main` were instance-based, something would need to construct an object before the program could bootstrap.
static
Can static methods be overridden?
Not in the polymorphic sense. Subclass static methods hide parent statics; resolution uses the compile-time type. Instance methods use dynamic dispatch; statics do not participate in that mechanism.
static polymorphism
Can one `try` have multiple `catch` blocks?
Yes. The first matching handler runs; put more specific types before broad `Exception`. At most one `catch` executes per thrown exception; you can also attach `finally` or use try-with-resources for closeable cleanup.
exceptions
What does `final` mean on variables, methods, and classes?
Variable: single assignment after initialization for fields/locals (with rules per context). Method: cannot be overridden. Class: cannot be subclassed. `final` does not make objects immutable—only the reference binding or override/inheritance surface.
final
When might `finally` not run?
If the JVM exits (`Runtime.exit`), if the thread is abruptly terminated in a fatal fault, or if `finally` itself throws (masking earlier exceptions—avoid heavy logic there). Do not rely on `finalize`—modern code uses try-with-resources and explicit lifecycle.
exceptions

2Java Intermediate Interview Questions

Strings beyond basics, singleton patterns, collections, threading introductions, reflection trade-offs, and API comparisons.

Strings, builders, and core APIs

Besides security, why are strings immutable in Java?
String pool / interning needs immutable content to be safe to share. Hash-based structures (`HashMap`) assume stable `hashCode` for the lifetime used as a key. Concurrency: readers need no locks for read-only shared `String` instances.
String concurrency
What is a singleton and a simple safe pattern?
A singleton restricts a class to one instance. Lazy_holder idiom: `private` constructor + `static` nested class that the JVM initializes on first access (`getInstance()`). For enum singleton, Joshua Bloch’s style gives serialization safety with minimal code.
design-patterns
`String` vs `StringBuilder` vs `StringBuffer`?
`String` is immutable (each “change” allocates anew unless optimized away). `StringBuilder` is mutable and not synchronized—preferred in single-threaded string assembly. `StringBuffer` is mutable and synchronized—legacy multi-thread append scenarios; often replaced by builders plus local confinement.
String
Interfaces vs abstract classes (modern Java)?
Interfaces define behavior contracts; since Java 8+ they may include `default` and `static` methods. A class implements many interfaces but extends one class. Abstract classes factor shared state and partial implementation when a strong class hierarchy makes sense.
OOP
`HashMap` vs `Hashtable`?
`Hashtable` is legacy, synchronized on every operation, and disallows `null` keys/values. `HashMap` is unsynchronized (use `ConcurrentHashMap` when you need concurrency, not `Hashtable`). Prefer `HashMap` for new code unless you integrate with very old APIs.
collections

Threads, reflection, pass-by-value

Two common ways to create a thread?
Subclass `Thread` (discouraged for domain modeling) or implement `Runnable`/`Callable` and pass to `new Thread(runnable).start()`. `ExecutorService` is preferred in applications to manage pooling and lifecycle.
concurrency
Why is reflection both powerful and risky?
Reflection inspects and invokes members without compile-time linkage—great for frameworks. Downsides: breaks encapsulation, slower than direct calls, weaker compile-time safety, and sensitive to module access rules on newer JDKs.
reflection
Does Java pass by reference or value?
Always pass-by-value of the parameter slot: primitives copy bits; references copy the pointer value (not the object). Mutating object fields through the copied reference affects the shared object; reassigning the parameter does not replace the caller’s variable.
semantics
Why might `char[]` be preferred over `String` for secrets?
You can overwrite a char array when done, shrinking the window secrets sit in memory. `String` is immutable and may linger in the heap/pool longer than needed. Modern APIs also use `char[]`, ByteBuffer, or platform secure stores for credentials.
security

3Java Interview Questions for Experienced

Composition vs inheritance, advanced operators, synchronization, varargs, UTF-16 quirks, and framework-aware answers.

Design & runtime

Why is composition often favored over inheritance?
Flexible wiring: behaviors are plugged in behind small interfaces without locking a deep hierarchy. Testing: collaborators can be mocked or faked without a rigid superclass. Evolvability: fewer brittle dependencies on base-class internals compared to wide inheritance trees.
design
Difference between `>>` and `>>>`?
`>>` sign-extends (arithmetic right shift for two’s complement). `>>>` zero-fills the top bits—useful for treating `int` bit patterns as unsigned in shifts. Use `Integer.rotateRight/Left` for rotation, not shifts, when that is the intent.
bitwise
`new` vs reflective `Constructor.newInstance` / older `Class.newInstance` patterns?
`new` requires a compile-time type. Reflection loads `Class<?>` objects at runtime—useful for plugins or configuration-driven wiring. Reflective creation can throw checked `ReflectiveOperationException` variants; access checks follow module and security rules.
reflection
Why is synchronization needed?
Multiple threads mutating shared mutable state without coordination create data races and torn reads/writes. `synchronized`, `java.util.concurrent` locks/atomics, or message passing (no sharing) restore correctness. Prefer `ConcurrentHashMap` over locking whole maps in servers.
concurrency
What does `String... args` mean?
Varargs compile to an array parameter; callers may pass zero or more positional arguments or an explicit array. Use when arity varies but type is uniform. Beware overload + varargs + null ambiguity pitfalls in API design.
syntax

Ecosystem (Spring touchpoints)

Name common Spring bean scopes.
singleton (one per container by default), prototype (new instance per resolve), and web scopes request/session/application. Choose prototype when stateful per usage or non-shareable resources are required; most services stay singleton if stateless.
Spring

4Java Programming Interview Questions

Short coding-style prompts with reference implementations you can rehearse aloud or type in our online practice flow.

Recursion & arrays

Check if a string is a palindrome using recursion.
Reference code
static boolean isPalindrome(String s, int lo, int hi) {
    if (lo >= hi) return true;
    if (s.charAt(lo) != s.charAt(hi)) return false;
    return isPalindrome(s, lo + 1, hi - 1);
}
Compare characters from both ends inward. If any mismatch, return false; if pointers cross, true.
recursion
Print Fibonacci numbers with a simple recursive helper.
Reference code
static void fib(int a, int b, int left) {
    if (left == 0) return;
    int c = a + b;
    System.out.print(c + " ");
    fib(b, c, left - 1);
}
Carry forward the last two values; base case stops after N prints. For production N large, switch to iterative or matrix exponentiation.
recursion
Find one missing number from 1..n in an unsorted array of unique ints.
Reference code
static int missing(int[] a) {
    int n = a.length + 1;
    long expected = (long) n * (n + 1) / 2;
    long sum = 0;
    for (int v : a) sum += v;
    return (int) (expected - sum);
}
Use Gauss sum `n*(n+1)/2` minus array sum in O(n) time, O(1) space. XOR trick also works to avoid overflow concerns in theory—still prefer `long` sums in interviews when n is large.
arrays

Strings & search

Test if two strings are anagrams (Ascii, case-sensitive variant).
Reference code
static boolean isAnagram(String a, String b) {
    if (a.length() != b.length()) return false;
    int[] c = new int[256];
    for (int i = 0; i < a.length(); i++) {
        c[a.charAt(i)]++;
        c[b.charAt(i)]--;
    }
    for (int v : c) if (v != 0) return false;
    return true;
}
Early length check, count characters with an int[256] or sort char arrays—O(n) vs O(n log n).
strings
Recursive binary search returning boolean.
Reference code
static boolean binSearch(int[] a, int key, int lo, int hi) {
    if (lo > hi) return false;
    int mid = lo + (hi - lo) / 2;
    if (a[mid] == key) return true;
    if (key < a[mid]) return binSearch(a, key, lo, mid - 1);
    return binSearch(a, key, mid + 1, hi);
}
Halve search space by comparing mid to key; beware `int mid = lo + (hi - lo) / 2` to avoid overflow.
search

5Tricky Java Interview Questions

Edge cases that trip panelists: immutability pitfalls, `finally` returns, char arithmetic, overload ambiguity.

Puzzles

Why can `s += "b"` on a String create extra objects?
`String` is immutable. `+=` lowers to `StringBuilder` operations under the hood in modern compilers, but you still materialize new `String` instances as results. Tight loops should use an explicit `StringBuilder` with estimated capacity.
String performance
Why does `System.out.println('a' + 'b');` print a number?
Single-quoted literals are `char`. `+` promotes chars through numeric addition unless at least one operand is a `String`. Use `"" +` or `String.valueOf`** to force textual concatenation.
chars
If both `try` and `finally` return a value, which wins?
The `finally` return overrides the `try` (or `catch`) return after `finally` runs. This surprises many readers—avoid non-trivial returns inside `finally`.
exceptions
Why is removing index `0` from `ArrayList` expensive?
Shift left: all tail elements move one slot → O(n) for one removal at the front. LinkedList can remove head in O(1) but loses random-access benefits—choose structure by access pattern.
collections

6Scenario-Based Java Interview Questions

Production thinking: latency, OOM, idempotency, concurrency, and observability.

What interviewers ask when they want judgment

The service slows down after several hours. What do you check first?
Heap/GC logs and metaspace; thread pool saturation; connection pools to databases; cache unbounded growth; recent deploy or config changes. Correlate with latency percentiles and async queue depths before micro-optimizing code.
ops
You hit `OutOfMemoryError: Java heap space`. Name three realistic causes.
A true leak (static caches forever), under-sized heap for legitimate working set, and allocation spikes (large batch jobs) that exceed limits. Profile with heap dumps and allocation profiling rather than guessing.
memory
A background job sometimes runs twice. How do you keep outcomes safe?
Idempotent handlers keyed by business IDs, unique constraints in the database, or a processed-events table / outbox with transactional writes. Combine with at-least-once messaging semantics consciously.
reliability

7Java Memory Management Interview Questions

Heap vs stack recap, reachability, leaks, references, and GC intuition.

Quick hits

What is garbage collection’s main goal?
Automatically reclaim unreachable objects so programmers avoid manual `free`. Throughput, pause-time, and footprint goals vary by collector (`G1`, `ZGC`, `Shenandoah`, …).
GC
When is an object eligible for GC?
When no strong reference chain exists from GC roots (threads, statics, JNI roots, etc.). Circular graphs with no external roots are also collectable.
GC
What does a memory leak mean in Java?
Objects stay strongly reachable longer than intended—often listeners, caches, or thread-locals—so the heap grows until failures occur.
memory

8Java 11 Interview Questions

LTS rationale, `var`, HTTP client, string helpers, and migration notes.

Java 11 topics

Why do enterprises standardize on Java 11 LTS?
Long-term support cadence with predictable security updates, modern language features (`var`, nicer APIs), and a stepping stone before newer LTS releases. Libraries gradually dropped older JDK support.
versions
What is `var` and where can it appear?
Local variable type inference—only where the type is obvious from the initializer. Not for fields, parameters, or uninitialized locals without initializer. It’s syntactic sugar; bytecode still carries concrete types.
syntax
What did `java.net.http.HttpClient` change for developers?
First-class HTTP/2, async API, and a cleaner model than legacy `HttpURLConnection` for many apps—though stacks on Netty/Jetty still dominate for advanced needs.
HTTP

9Java Full Stack Developer Interview Questions

REST shape, auth vs authz, transactions, ORM pitfalls, and deployment.

Backend + web concerns

How do you sketch a REST API in Spring Boot at a high level?
Resources map to nouns in URLs; `@RestController` methods map HTTP verbs to use cases; DTOs decouple persistence entities; validation (`@Valid`) at the edge; consistent error envelopes; pagination for lists. Keep controllers thin—services own orchestration.
Spring REST
Authentication vs authorization?
Authentication: who you are (login, tokens). Authorization: what you may do (roles/scopes/policies). Spring Security chains filters for the former and method/URL security for the latter.
security
What is the N+1 query problem in JPA/Hibernate?
Loading N parents then lazy-loading children one by one yields 1 + N queries. Mitigate with `JOIN FETCH`, entity graphs, or batch fetching tuned to your access path.
ORM

10Conclusion

How to use this guide with InterviewForge AI mock interviews and ATS prep.

Next steps

How should you combine reading with practice?
Read a section, then explain answers out loud without looking. Use AI mock interviews on InterviewForge for follow-up probes. Pair conceptual cards with 1–2 small coding reps weekly. Track misses in a checklist and regenerate variants with the OpenAI panel on this page.
study-plan

11Java MCQ (sample)

Rapid checks similar to end-of-guide quizzes on large interview sites.

Practice set

Which component typically performs JIT compilation of hot bytecode?

  • A.JDK
  • B.JVM
  • C.JRE only
  • D.`javac` only

`String a = new String("x"); String b = "x";` What does `a == b` evaluate to?

  • A.true
  • B.false
  • C.Compilation error
  • D.Undefined

During many stop-the-world GC events, application threads are typically:

  • A.Always running unaffected
  • B.Paused
  • C.Duplicated
  • D.Run in reverse order

Which collection allows one `null` key in typical `HashMap` semantics?

  • A.`Hashtable`
  • B.`TreeMap` always
  • C.`HashMap`
  • D.`ConcurrentSkipListMap`

If a method declares `throws IOException`, callers must:

  • A.Ignore it
  • B.Catch or declare
  • C.Mark method native
  • D.Use varargs

Composition (strong ownership) vs aggregation is mainly about:

  • A.Keyword `static`
  • B.Lifecycle coupling of parts
  • C.`equals` hashing
  • D.String pool usage