Java Primer — From Zero to Working Code
"The language the world's banks and enterprise back-ends actually run on — taught from your very first line, with every incantation explained."
01 · The hookThe Machine Round That Sorts Freshers Into Two Piles
This appendix teaches Java from zero and gets you through the fresher interview round. The dividing line in that room is not talent — it is whether you learned Java by reading about it or by running it.
"I interview about forty final-year students a day during placement week. My opener is
always the same two questions: why does Java insist your main method live inside a
class? and what's the difference between == and
.equals()?
The candidates split cleanly. One group recites — 'Java is purely object-oriented, equals compares content' — and then collapses on the first follow-up, because they memorized answers to questions they never actually hit.
The other group pauses, and you can see them remembering the bug: the
afternoon their login check failed because they compared two Strings with
==. Those candidates have written maybe five hundred lines of real Java.
They clear the round in fifteen minutes.
The difference isn't talent. It's whether the answers came from a PDF or from a compiler."
This appendix exists to put you in the second pile. It teaches Java from zero — no prior programming assumed, only general computer literacy — and it teaches by making you run every example, because the retention difference between reading Java and running Java is the difference Rajesh sees across the table. The target is roughly twelve honest hours: enough to write a complete small program, explain every line of it, and answer the fresher-interview canon from experience rather than memory.
Why start the engineering track with Java from zero, when the rest of the track assumes nine years of it? Two honest reasons.
First, the fundamentals are exactly what senior rounds go back to. The largest hiring pipelines — the services majors, the banks, the insurers — still open with core Java. An experienced candidate who fumbles the basics loses the room before the deep questions start.
Second, this chapter is the shared vocabulary for everything that follows. Chapter E2 goes under the hood of the JVM, and Chapter E3 drills three hundred senior questions.
So skim what you already know. Slow down wherever you find you cannot explain a line of code out loud. More on where this fits in section 13.
Even with zero programming behind you, you already hold the two big ideas.
A class is a printed form template — "Student Admission Form". An object is one filled-in copy of it. The office can print as many copies as it likes, each with its own name and marks, all sharing one layout.
A JVM is a universal player. One .mp3 file plays on any
phone, because every phone ships a player that understands the format. In the same way, one
compiled Java program runs on any machine, because every machine can install a JVM that
understands bytecode.
Everything in this appendix is those two ideas, worked out carefully.
02 · Getting set upOne JDK, One File, Every Word Explained
You install one thing — the JDK — and it contains everything else you have heard of. Then you write one file and run it, and every single word in that file has a reason.
Install a current long-term-support JDK — Java 21 (from
adoptium.net, free) or any
newer LTS. Everything in this appendix runs on 21 or later. Verify the install with
java --version.
Three terms will hit you immediately, and interviewers ask you to separate them. Here they are in one table.
| Term | Stands for | What it is |
|---|---|---|
| JVM | Java Virtual Machine | The program that runs compiled Java. |
| JRE | Java Runtime Environment | Historically the JVM plus the standard libraries — enough to run Java, not to build it. Since Java 11 it is not shipped separately, so treat it as a legacy interview term. |
| JDK | Java Development Kit | The full toolbox: the JVM, the libraries, and the compiler javac. This is what you just installed, and it contains the other two. |
The short version: you installed the JDK, and the JDK contains the other two.
javac compiles source to bytecode once; any OS with a JVM runs those identical bytes.Now the first program — and, unlike most courses, we're going to explain every word of it once, properly, because this incantation is exactly what freshers memorize and interviewers probe:
// Run directly, no separate compile step needed: java Hello.java
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java");
if (args.length > 0) {
System.out.println("You passed: " + args[0]);
}
}
}
Word by word. Six words, six deliberate decisions. Nothing in that line is magic, and by the end of this table you will know every one of them.
| Word | What it means | Why Java needs it here |
|---|---|---|
class Hello | Declares a class named Hello. | All Java code lives inside classes. There are no free-floating functions, so even the entry point needs a home. That is the honest answer to Rajesh's first question. |
public | Visible from outside the class. | The JVM launcher lives outside your code, so it must be able to see main in order to call it. |
static | Belongs to the class itself, callable without creating an object first. | The JVM has to start your program before any object of yours exists, so the entry point cannot require one. |
void | Returns nothing. | The program signals success or failure through an exit code, not through a return value. |
String[] args | An array of the command-line arguments. | So java Hello.java world puts "world" into args[0]. |
System.out.println | The standard output stream's print-line method. | It is the plainest way to make a program tell you what it did — which is most of how you will learn in this chapter. |
Picture it: JDK, JRE and JVM are nested, and one command chain turns source into output
The setup: You type two commands and the same three letters (JDK, JRE, JVM) keep appearing in error messages and interview questions.
javac Hello.java # step 1: compiler, ships only in the JDK
java Hello # step 2: launcher that starts a JVM
Make the invisible visible: The JDK contains the JRE (legacy term), which contains the JVM, and the two commands use different layers.
+---------------------- JDK (what you installed) ----------------------+
| javac, jar, jshell, javadoc ... <- development tools |
| +----------------- JRE (legacy name) -------------------------+ |
| | standard libraries: String, List, Files ... | |
| | +----------------------- JVM ---------------------------+ | |
| | | loads .class files, runs bytecode, manages memory | | |
| | +-------------------------------------------------------+ | |
| +--------------------------------------------------------------+ |
+-----------------------------------------------------------------------+
The trace: Follow the two commands one step at a time, and see where each can fail.
javac Hello.java
1. read Hello.java, check syntax and types ✓ no errors
2. write Hello.class (bytecode) ✓
java Hello
3. JVM starts, finds Hello.class ✓
4. JVM looks for public static void main(String[]) ✓
5. runs main, prints "Hello, Java" ✓
If step 1 fails: no Hello.class is written,
so step 3 fails: Error: Could not find or load main class Hello ✗
What you see: A successful run prints the greeting, and a failed compile leaves you with the launcher error instead.
$ javac Hello.java && java Hello
Hello, Java
$ java Hello # Hello.class was never produced
Error: Could not find or load main class Hello
Caused by: java.lang.ClassNotFoundException: Hello
Why: The compiler and the JVM are separate programs, so a compile failure never reaches the JVM and the launcher can only say that the class file is missing.
The fix: Read the javac output first and fix the first error it reports, then run java again.
What you see now: Once the compile passes, the same two commands print the greeting.
$ javac Hello.java && java Hello
Hello, Java
Picture it: what lands in args
Make the invisible visible: Command-line words become an array of Strings that main receives as args.
$ java Hello.java world
STACK (main's frame) HEAP
+--------------------+
| String[] args ●---+---------> [ length=1 | ●--> "world" ]
+--------------------+
args.length > 0 is true, so the program prints: You passed: world
- Interview takeaway: "The JDK is what you install: it holds the compiler
javac, the libraries and the JVM, andjavacturns source into bytecode that any JVM can run."
Aside: the newest JDKs let you write a bare void main()
with no class at all — pleasant for scratch files, and you'll meet it in blog posts. But every
interview, textbook, and production codebase uses the classic form, so that's the one this
primer teaches and uses throughout.
03 · Core JavaValues & Types — Primitives, Objects, and the String You Can't Change
Java makes you say what kind of thing every variable holds, before you use it. There are two families: primitives, which hold a value directly, and objects, which hold an arrow pointing at one.
Java is statically typed: every variable declares its type up front. The compiler refuses programs that violate those declarations, so a whole class of bugs dies before the program ever runs.
Values come in two families.
- Primitives are raw values stored directly, which makes them cheap and fast. There are eight, and four do almost all the daily work (table below).
- Objects are everything else, and a variable holds an arrow to them instead of the value itself.
| Type | Holds | Example | Notes |
|---|---|---|---|
int | Whole numbers | int marks = 78; | 32-bit; ceiling ≈ 2.1 billion — beyond that, long |
double | Decimals | double price = 199.99; | 64-bit floating point; the default for decimals |
boolean | true / false | boolean paid = true; | Only these two values — no 0/1 truthiness in Java |
char | One character | char grade = 'A'; | Single quotes; secretly a number (see Brain Power) |
Everything else is an object: created from a class, living on the heap, reached through a reference.
The object you'll touch most is String. It hides Java's most
interview-famous design decision: strings are immutable.
No method ever changes a String. Every "modification" quietly builds a new one.
// Run with: java Values.java
public class Values {
public static void main(String[] args) {
int count = 42;
double price = 199.99;
boolean paid = true;
char grade = 'A';
System.out.println(count + " " + grade + " " + paid); // 42 A true
// String: an object in double quotes. IMMUTABLE -- methods return
// new strings; the original never changes.
String name = "Asha";
System.out.println(name.length()); // 4
System.out.println(name.toUpperCase()); // ASHA -- a NEW string
System.out.println(name); // Asha -- untouched
// int vs Integer: primitive vs its object "wrapper". Both exist because
// collections (section 07) can only hold OBJECTS -- Integer is how an
// int rides along. Java converts between them automatically (boxing).
Integer boxed = count; // autoboxing: int -> Integer
int unboxed = boxed; // unboxing: Integer -> int
System.out.println(boxed + unboxed); // 84
// var: the compiler INFERS the type from the right-hand side.
// Still statically typed -- city is a String forever after this line.
var city = "Pune";
System.out.println(city.length()); // 4
// Casting: the safe direction is automatic; the lossy direction
// must be written out loud, so data loss is always visible.
double d = count; // int -> double: widens, automatic
int chopped = (int) price; // double -> int: TRUNCATES (not rounds!)
System.out.println(d + " " + chopped); // 42.0 199
// final: assign once, never reassign -- Java's constant.
final int MAX_ATTEMPTS = 3;
System.out.println(MAX_ATTEMPTS * 2); // 6
// The += trap: immutability means each += builds a WHOLE new string.
// Harmless at 5 iterations; an O(n²) disaster at 100,000.
String s = "";
for (int i = 0; i < 5; i++) s += i; // (loop syntax: next section)
System.out.println(s); // 01234
StringBuilder sb = new StringBuilder(); // the fix: a mutable buffer
for (int i = 0; i < 5; i++) sb.append(i);
System.out.println(sb.toString()); // 01234 -- one object, no waste
}
}
Why do int and Integer both exist? Performance honesty: a
million ints are a million bare numbers packed in memory; a million
Integers are a million objects with headers and references. Java kept primitives
for speed and added wrappers so numbers could live where only objects are allowed. Autoboxing
papers over the seam — until it doesn't, which is a star exhibit in
Watch it break.
Picture it: a primitive holds a value, a reference holds an arrow
The setup: Three variables from Values.java, one primitive and two references, and a method call whose result is thrown away.
int count = 42;
String name = "Asha";
Integer boxed = count;
name.toUpperCase(); // ❌ TRAP: result ignored, name is NOT changed
System.out.println(name);
Make the invisible visible: The stack frame stores the number itself for count but only arrows for the two objects.
STACK (main's frame) HEAP
+------------------------+
| int count = 42 |
| String name = ●------+------> [ String "Asha" ]
| Integer boxed = ●------+------> [ Integer 42 ]
+------------------------+
primitive: the slot holds the value. reference: the slot holds an arrow.
The trace: Follow name.toUpperCase(); when nobody keeps the result.
name.toUpperCase();
1. follow the arrow in name to String "Asha" ✓
2. build a NEW String "ASHA" on the heap ✓
3. return an arrow to "ASHA"
4. nobody stores that arrow, "ASHA" becomes garbage ✗
5. name still points at "Asha" (String is immutable) ✓
What you see: The original string prints unchanged, as if the call never happened.
Asha
Why: Strings are immutable, so every method that seems to change one returns a new String and leaves the original alone.
The fix: Keep the arrow the method hands back.
name = name.toUpperCase(); // ✅ FIX: re-aim name at the new String
System.out.println(name);
What you see now: The variable now points at the new String.
ASHA
Picture it: == compares arrows, equals compares contents
The setup: Three Strings holding the same letters, two made from literals and one made with new.
public class StringEq {
public static void main(String[] args) {
String a = "hi";
String b = "hi";
String c = new String("hi");
System.out.println(a == b); // ❌ TRAP when used for content checks
System.out.println(a == c); // ❌ TRAP
System.out.println(a.equals(c));
}
}
Make the invisible visible: Literals share one object in the string pool, while new String always builds a separate object on the heap.
STACK HEAP
a ●-----+
+-----------> [ pooled String "hi" ] (one shared literal)
b ●-----+
c ●-----------------> [ String "hi" ] (separate object from new)
The trace: Each comparison asks a different question.
a == b same arrow? yes, both aim at the pooled "hi" ✓ true
a == c same arrow? no, two different objects ✗ false
a.equals(c) same chars? h,i versus h,i ✓ true
What you see: Equal contents, yet == disagrees with itself.
true
false
true
Why: == on references compares the arrows (identity), while String.equals compares the characters. Only literals are pooled automatically, so == works by luck for them and fails for anything built at runtime.
The fix: Use equals for content, and put the literal first so a null input cannot crash.
System.out.println(a.equals(b)); // ✅ FIX: compare contents
System.out.println(a.equals(c));
System.out.println("admin".equals(input)); // ✅ FIX: null-safe, literal first
What you see now: Both content checks agree, whichever way the string was built.
true
true
Picture it: the Integer cache makes == work for 127 and fail for 128
The setup: Two pairs of boxed integers compared with ==.
Integer p = 127, q = 127;
Integer r = 128, s = 128;
System.out.println(p == q); // ❌ TRAP: works only inside the cache range
System.out.println(r == s); // ❌ TRAP
Make the invisible visible: Autoboxing is really a call to Integer.valueOf, and that method reuses cached objects for -128 to 127 only.
Integer p = Integer.valueOf(127); // returns the cached object
Integer q = Integer.valueOf(127); // returns the SAME cached object
Integer r = Integer.valueOf(128); // outside the cache: new object
Integer s = Integer.valueOf(128); // outside the cache: another new object
STACK HEAP
p ●--+
+--> [ cached Integer 127 ] (built once, shared)
q ●--+
r ●-----> [ Integer 128 ]
s ●-----> [ Integer 128 ] (equal value, different object)
The trace: Same arrow or not decides the answer.
p == q same arrow? yes (cache hit) ✓ true
r == s same arrow? no (two objects) ✗ false
What you see: Two lines that look identical give different answers.
true
false
Why: The cache covers -128 to 127 by default, so == on boxed numbers is correct for small values and wrong for the rest.
The fix: Compare boxed values with equals.
System.out.println(p.equals(q)); // ✅ FIX
System.out.println(r.equals(s)); // ✅ FIX
What you see now: Both comparisons give the correct answer.
true
true
Picture it: why += on a String in a loop gets slow
The setup: The s += i loop from Values.java, scaled up.
String s = "";
for (int i = 0; i < 100_000; i++) s += i; // ❌ TRAP: new String every pass
Make the invisible visible: Each pass allocates a brand-new String and copies everything built so far into it.
pass 1: s --> "0" old "" is garbage
pass 2: s --> "01" copied 1 char, old "0" is garbage
pass 3: s --> "012" copied 2 chars, old "01" is garbage
...
pass n: s --> one long String, n-1 earlier Strings already garbage
The trace: The copying cost adds up as 1 + 2 + 3 + ... characters.
n = 5 copies 0+1+2+3+4 = 10 chars ✓ harmless
n = 100,000 copies about n*(n-1)/2 = 5 billion ✗ O(n²)
What you see: Timing grows much faster than the loop count.
# illustrative output
+= loop, 100000 passes: 4200 ms
+= loop, 200000 passes: 17000 ms (twice the work, four times the time)
Why: Immutability forces a full copy on every append, so the total work is quadratic.
The fix: Use a StringBuilder, one mutable buffer that appends in place.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100_000; i++) sb.append(i); // ✅ FIX
String s = sb.toString();
What you see now: The same loop finishes in a blink and scales linearly.
# illustrative output
StringBuilder, 100000 passes: 3 ms
StringBuilder, 200000 passes: 6 ms
Picture it: what boxed + unboxed really compiles to
Make the invisible visible: Autoboxing and unboxing are plain method calls that the compiler inserts for you.
Integer boxed = Integer.valueOf(count); // from: Integer boxed = count;
int unboxed = boxed.intValue(); // from: int unboxed = boxed;
That second line is a method call on an object, so it can fail when boxed is null. The collections section shows that failure with a HashMap.
- Interview takeaway: "
==on objects compares references, so I useequalsfor Strings and boxed numbers. Strings are immutable, which is why+=in a loop is quadratic andStringBuilderis the fix."
Predict all four lines before running them. Hint: + means
"add" for numbers but "join" for strings, and Java evaluates left to right. A
char is secretly a number (its Unicode value — 'A' is 65).
public class Predict1 {
public static void main(String[] args) {
System.out.println(1 + 2 + "3");
System.out.println("1" + 2 + 3);
System.out.println('A' + 1);
System.out.println((char) ('A' + 1));
}
}
Reveal the answer
33 — left to right: 1 + 2 is arithmetic (3), then
3 + "3" joins. 123 — the String comes first, so everything after
it joins. 66 — 'A' is 65, and char + int is
arithmetic. B — same 66, but the cast says "show it as a character again".
Two real lessons: operator meaning depends on types, and chars are numbers wearing
costumes.
1 + 2 + "3" (1 + 2) + "3" -> 3 + "3" -> "33"
"1" + 2 + 3 ("1" + 2) + 3 -> "12" + 3 -> "123"
'A' + 1 65 + 1 -> 66
(char) ('A'+1) (char) 66 -> 'B'
Quick reference — Values and types
- statically typed
- Every variable declares its type up front. The compiler rejects programs that break those declarations, so a whole class of bugs dies before the program runs.
- primitive
- A raw value stored directly. Eight of them; four do the daily work —
int,double,boolean,char. - object
- Created from a class, lives on the heap, reached through a reference.
- String is immutable
- No method ever changes a String. Every "modification" quietly builds a new one.
- int vs Integer
intis a bare number;Integeris an object with a header. Primitives for speed, wrappers so numbers can go where only objects are allowed.- autoboxing
- Java converting between the two automatically. It papers over the seam until it doesn't — see Watch it break.
04 · Core JavaControl Flow — Decisions, Loops, and the Array That Won't Grow
The three ways a program stops running straight down the page: choose a branch, repeat a block, or step through a fixed row of values. The catch at the end is that an array's size can never change.
Control flow is how a program stops being a list of statements and starts making decisions. Java's kit:
- Branching:
if / else, andswitchfor picking one branch among many. - Repeating: three loops,
for, enhancedforandwhile.
One historical wart to know up front: the classic switch falls
through from case to case unless you write break. It has been a genuine bug
source for thirty years, and modern Java added an arrow form that fixes it.
Learn both. Interviews ask about the classic, and real code prefers the arrow.
// Run with: java Control.java
public class Control {
public static void main(String[] args) {
int marks = 78;
// if / else if / else -- parentheses and braces are mandatory furniture
if (marks >= 90) {
System.out.println("distinction");
} else if (marks >= 60) {
System.out.println("first class"); // <- this one prints
} else {
System.out.println("keep going");
}
// classic switch: falls THROUGH unless you break (see Brain Power)
String day = "SAT";
switch (day) {
case "SAT":
case "SUN":
System.out.println("weekend");
break;
default:
System.out.println("weekday");
}
// modern arrow switch (Java 14+): no fall-through, and it's an
// EXPRESSION -- it produces a value you can assign.
String kind = switch (day) {
case "SAT", "SUN" -> "weekend";
default -> "weekday";
};
System.out.println(kind); // weekend
// Loop 1: the counting for-loop (init; keep-going test; step)
for (int i = 1; i <= 3; i++) {
System.out.println("attempt " + i); // attempt 1 / 2 / 3
}
// An array: a FIXED-length row of same-typed slots.
int[] scores = {72, 89, 91};
// Loop 2: enhanced-for -- "for each score in scores", no index bookkeeping
int total = 0;
for (int score : scores) total += score;
System.out.println(total / scores.length); // 84 -- integer division!
// Loop 3: while -- loop as long as a condition holds
int retries = 3;
while (retries > 0) retries--;
System.out.println(retries); // 0
// Arrays cannot grow. This line would CRASH with
// ArrayIndexOutOfBoundsException -- the itch collections will scratch:
// scores[3] = 100;
System.out.println(scores.length); // 3 -- .length is a field, no ()
}
}
Sit with that last block for a second, because it holds two things worth catching.
An array's size is fixed at creation, forever. Real programs need
containers that grow — a library adding books, a cart adding items. Java's answer is the
collections framework in section 07. When you get there,
ArrayList will feel earned rather than announced.
And look at total / scores.length. Both sides are
int, so Java does integer division and throws away any remainder. Here
252 / 3 = 84 exactly, so the problem hides. That is precisely why it is a classic trap, and it
is demonstrated properly in Watch it break.
Picture it: an array is one fixed row, and the variable holds an arrow to it
The setup: The scores array from Control.java, with one write past its end.
int[] scores = {72, 89, 91};
scores[3] = 100; // ❌ TRAP: valid indexes are 0, 1 and 2
Make the invisible visible: The array lives on the heap with its length stored beside the slots.
STACK HEAP
scores ●--------------> [ length = 3 ]
[ 72 ][ 89 ][ 91 ]
index 0 1 2 (index 3 does not exist)
The trace: Java checks every index against the length before it touches a slot.
scores[3] = 100
1. follow the arrow in scores to the array ✓
2. is 3 < length (3)? no ✗
3. throw ArrayIndexOutOfBoundsException, nothing is written
What you see: The program stops with the index and the length in the message.
# illustrative output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Control.main(Control.java:41)
Why: An array's length is fixed when it is created, and Java checks bounds so a stray index can never corrupt neighbouring memory.
The fix: Build a bigger array and copy, or better, use an ArrayList (section 07).
int[] bigger = java.util.Arrays.copyOf(scores, 4); // ✅ FIX: new row of 4, values copied
bigger[3] = 100;
System.out.println(java.util.Arrays.toString(bigger));
System.out.println(scores.length);
What you see now: The new array has the extra slot, and the old one is untouched.
[72, 89, 91, 100]
3
Picture it: copying an array variable copies the arrow
The setup: A second variable assigned from the first, then a write through the second.
int[] scores = {72, 89, 91};
int[] copy = scores; // ❌ TRAP: copies the arrow, not the row
copy[0] = 0;
System.out.println(scores[0]);
Make the invisible visible: Both variables aim at the same single array.
STACK HEAP
scores ●--+
+-----------> [ 72 | 89 | 91 ] (ONE array, two names: an alias)
copy ●--+
The trace: The write goes through one name and shows up under the other.
copy[0] = 0 follow copy's arrow, write 0 into slot 0 ✓
scores[0] follow scores' arrow to the same array ✗ reads 0, not 72
What you see: The original array changed although only copy was written.
0
Why: Assignment copies what the variable holds, and for an array that is the arrow.
The fix: Make a real second row with clone().
int[] copy = scores.clone(); // ✅ FIX: new array with the same values
copy[0] = 0;
System.out.println(scores[0]);
What you see now: The original keeps its value.
72
Picture it: what the enhanced for compiles to
Make the invisible visible: For an array, for (int score : scores) is an ordinary indexed loop written for you.
int[] arr = scores; // hidden copy of the arrow
int len = arr.length;
for (int i = 0; i < len; i++) {
int score = arr[i]; // your loop variable
total += score; // your loop body
}
Picture it: integer division throws the remainder away
The setup: An average computed from three scores whose total is 253.
int total = 253;
int a = total / 3; // ❌ TRAP: int / int
double b = total / 3; // ❌ TRAP: still int / int, then widened
double c = total / 3.0; // ✅ FIX: one side is double
The trace: The types decide the arithmetic before the assignment is looked at.
a = 253 / 3 int / int -> 84 remainder 1 dropped ✗
b = 253 / 3 int / int = 84 -> 84.0 widened too late ✗
c = 253 / 3.0 int -> double, double / double -> 84.33333333333333 ✓
What you see: Printing the three variables shows two wrong answers and one right one.
a = 84
b = 84.0
c = 84.33333333333333
Why: If both operands are int, Java does integer division, and the target variable's type is not consulted.
- Interview takeaway: "Arrays have a fixed length and bounds are checked, so you get
ArrayIndexOutOfBoundsExceptioninstead of corrupted memory. Assigning an array to another variable copies the reference, so both names alias one array."
Every break below has been deleted. What prints?
public class Predict2 {
public static void main(String[] args) {
int n = 2;
switch (n) {
case 1: System.out.println("one");
case 2: System.out.println("two");
case 3: System.out.println("three");
default: System.out.println("other");
}
}
}
Reveal the answer
two, then three, then other. Execution jumps to
the matching case and then falls through every case below it until a
break or the end. That's not a quirk — it's the design (inherited from C),
occasionally useful for grouping cases, mostly a bug factory. The arrow form
(case 2 -> ...) simply cannot fall through, which is why modern code
prefers it.
n = 2
case 1: no match, skipped
case 2: match ✓ prints "two"
case 3: not tested, falls in ✗ prints "three"
default: falls in ✗ prints "other"
Quick reference — Control flow
- The three shapes
- Choose a branch (
if/switch), repeat a block (while/for), or step through a fixed row of values (the enhancedfor). - Arrays have a fixed size
- Set at creation, forever. This is what makes the collections framework in section 07 necessary rather than optional.
- Integer division
int / intthrows away the remainder. It hides whenever the division happens to come out exact.
05 · Core JavaMethods — Signatures, Overloading, and What "Pass By Value" Really Means
A method is a named block of code you can call. The one fact interviewers probe here: Java always hands a method a copy of what your variable holds — which behaves very differently for a number than for an arrow.
A method is a named, reusable block: inputs in the parentheses, output type before the
name. A method's signature is its name plus its parameter types — and
Java lets several methods share a name as long as their signatures differ. That's
overloading: the compiler picks the right one from the arguments you pass.
You've been using it all along — println is overloaded for Strings, ints,
doubles, and more.
// Run with: java Methods.java
public class Methods {
// Overloading: same name, different parameter lists -- the compiler
// picks by matching your arguments against each signature.
static int area(int side) { return side * side; }
static int area(int w, int h) { return w * h; }
static double area(double radius) { return Math.PI * radius * radius; }
// static = belongs to the class, callable with no object -- which is
// why main can call these directly. (Instance methods: next section.)
static int square(int n) { return n * n; }
// The pass-by-value demo. Java copies whatever is IN the variable:
// for int, the number itself; for an array, the REFERENCE (the arrow).
static void tryToChange(int n, int[] arr) {
n = 999; // changes this method's private copy of the number
arr[0] = 999; // follows the copied arrow to the ONE shared array
}
public static void main(String[] args) {
System.out.println(area(4)); // 16 -- picked area(int)
System.out.println(area(4, 5)); // 20 -- picked area(int, int)
System.out.println(area(2.0)); // 12.56... -- picked area(double)
System.out.println(square(12)); // 144
int x = 1;
int[] xs = {1, 2, 3};
tryToChange(x, xs);
System.out.println(x); // 1 -- untouched: n was a copy
System.out.println(xs[0]); // 999 -- changed THROUGH the arrow
}
}
That last pair of prints is the single most misunderstood fact in Java. The rule itself is one line: Java is always pass-by-value. A method receives a copy of what the variable holds.
The subtlety is entirely in what a variable holds, and it differs between the two kinds of variable.
- An
intvariable holds the number itself. The copy is a fresh number, so reassigning it inside the method changes nothing outside. - An array variable — or any object variable — holds a reference, an arrow pointing to the object on the heap. The copy is a copy of the arrow, still aimed at the same object.
That second case is where people get caught, because two different actions have two different outcomes. Reassigning the parameter re-aims your copy of the arrow, and the caller sees nothing. Mutating through the arrow modifies the one shared object, and the caller sees everything.
Draw it once and it stays drawn:
arr[0] = 999 edits the one shared array, while n = 999 edits a private copy.Picture it: two stack frames, one shared array
Make the invisible visible: While tryToChange runs, the stack holds two frames, and each argument was copied into the new one.
STACK HEAP
+------------------------+ (main)
| int x = 1 |
| int[] xs = ●-----------+-----------+
+------------------------+ |
+------------------------+ (tryToChange, on top) +--> [ 1 | 2 | 3 ]
| int n = 1 (copy) | |
| int[] arr = ●----------+-----------+ (copy of the arrow)
+------------------------+
The trace: Two assignments inside the method have different reach.
n = 999 change the number inside tryToChange's own frame ✓ x in main is still 1
arr[0] = 999 follow the copied arrow to the shared array ✗ xs[0] in main becomes 999
return tryToChange's frame is popped, n and arr vanish
What you see: The caller sees the array change but not the int.
1
999
Why: Java copies what the variable holds: a number for int, an arrow for an array.
The fix: If the caller needs a new number, return it and assign it, since a method can never reassign the caller's variable.
static int bump(int n) { return n + 1; }
int x = 1;
x = bump(x); // ✅ FIX: the caller stores the result
System.out.println(x);
What you see now: The caller's variable holds the new number.
2
Picture it: which overload the compiler picks
Make the invisible visible: The compiler matches each call against the signatures before the program runs.
| Call | Picked | Outcome |
|---|---|---|
area(4) | area(int) | Works: 16 |
area(4, 5) | area(int, int) | Works: 20 |
area(2.0) | area(double) | Works: 12.56... |
area('a') | area(int), char widens to int | Works: 9409 (97 * 97) |
area(4L) | area(double), long widens to double (it would have to narrow to fit int) | Works: 50.26... |
area("4") | none | Compile error: no suitable method found for area(String) |
- Interview takeaway: "Java is always pass-by-value. For an object the value is a reference, so a method can mutate the shared object through its copy, but reassigning the parameter never affects the caller."
One character changed from the demo above — the method now reassigns the array parameter instead of mutating through it. What prints?
public class Predict3 {
static void reassign(int[] arr) {
arr = new int[] {7, 7, 7}; // aim the LOCAL copy at a new array
}
public static void main(String[] args) {
int[] data = {1, 2, 3};
reassign(data);
System.out.println(data[0]);
}
}
Reveal the answer
1. reassign re-aimed its own copy of the arrow at a brand-new
array; the caller's arrow never moved, and the new array is quietly garbage-collected. If
Java were "pass-by-reference", data[0] would be 7. This exact question — with
exactly this trap — is a fresher-round staple.
before: data ●-----+-----> [ 1 | 2 | 3 ]
arr ●-----+ (copy of the arrow)
after arr = new int[] {7, 7, 7}:
data ●----------> [ 1 | 2 | 3 ] caller's arrow never moved
arr ●----------> [ 7 | 7 | 7 ] only the local copy was re-aimed
after return: arr is gone, [ 7 | 7 | 7 ] is unreachable -> garbage
Quick reference — Methods
- signature
- The method's name plus its parameter types. This is what the compiler matches a call against.
- overloading
- Same name, different parameter types. Chosen at compile time, by the declared types.
- Java is always pass-by-value
- A method gets a copy of what the variable holds. Always. There is no exception to this rule.
- …so why do objects seem different?
- Because an object variable holds an arrow, not the object. You get a copy of the arrow. Re-aiming your copy changes nothing for the caller; changing what it points at changes everything.
06 · The heart of JavaObjects — Design, Not Ceremony
A class is a template; an object is one filled-in copy. The four pillars — encapsulation, inheritance, polymorphism, abstraction — are four answers to one question: how do you keep a growing program from turning into a knot?
Encapsulation: bundling data with the rules that keep it valid
Here's where Java stops being syntax and starts being a design philosophy. A class bundles
data (fields) with the operations that keep that data valid (methods) — and
everything else in OOP is elaboration on that bundling. Let's build a Student
gradually, adding each piece because a problem demands it, not as ritual:
// Run with: java Student.java
public class Student {
// private: no code outside this class touches these directly.
// This is ENCAPSULATION -- and it's protection, not paperwork.
private final String id; // final field: set once in the constructor
private String name;
private int marks;
// Constructor: runs at `new`. Its job is to hand back a VALID object
// or refuse loudly -- garbage never gets in.
public Student(String id, String name, int marks) {
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("marks must be 0-100, got " + marks);
}
this.id = id; // `this.id` = the field; `id` = the parameter
this.name = name;
this.marks = marks;
}
// Getters: controlled READ access.
public String getName() { return name; }
public int getMarks() { return marks; }
// A setter WITH A RULE -- the entire point of private fields:
// the class defends its own invariants, in one place, forever.
public void updateMarks(int marks) {
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("bad marks: " + marks);
}
this.marks = marks;
}
@Override
public String toString() { // what println prints for this object
return id + " " + name + " (" + marks + ")";
}
public static void main(String[] args) {
Student s = new Student("S-101", "Asha", 78);
System.out.println(s.getName()); // Asha
s.updateMarks(83);
System.out.println(s); // S-101 Asha (83)
// s.marks = -50; // does not compile: marks is private -- THE POINT.
// Without private, any of 400 files could write -50 and you'd
// debug all 400. With it, bad marks can only die in two methods.
}
}
Notice what private plus getters actually buys you. Not bureaucracy — a
single choke point for every rule about the data. That is the honest version of
"encapsulation", and it is the version worth saying in an interview.
Picture it: what the constructor and private protect
The setup: Another class tries to build a Student with impossible marks, and then to write the field directly.
public class Roster {
public static void main(String[] args) {
Student s = new Student("S-101", "Asha", 78);
s.updateMarks(83); // ✅ goes through the rule
// s.marks = -50; // ❌ TRAP: bypass the rule
Student bad = new Student("S-102", "Ravi", 150); // ❌ TRAP: invalid input
}
}
Make the invisible visible: A valid Student is one heap object whose fields only its own methods can write.
STACK HEAP
s ●------------------> [ Student
id ●--> "S-101"
name ●--> "Asha"
marks = 83 (private: only Student's methods write it) ]
The trace: The constructor refuses the bad input before any reference is handed back.
new Student("S-102", "Ravi", 150)
1. JVM allocates a blank Student on the heap ✓
2. constructor runs: marks 150 > 100? yes ✗ throw IllegalArgumentException
3. the new expression never returns a reference, so bad stays unassigned ✓
(no half-built Student ever reaches the caller)
What you see: Both attempts are stopped, one by the compiler and one at runtime.
// compile error for s.marks = -50 (written in another class):
error: marks has private access in Student
// runtime error for new Student("S-102", "Ravi", 150):
Exception in thread "main" java.lang.IllegalArgumentException: marks must be 0-100, got 150
at Student.<init>(Student.java:12)
- Works:
s.updateMarks(83);from any class, because the method validates the value. - Fails:
s.marks = -50;from another class, with the compile errormarks has private access in Student. - Fails:
s.updateMarks(-5);, withIllegalArgumentException: bad marks: -5at runtime.
Why: Private fields mean every write must pass through code the class controls, so the rules live in one place.
- Interview takeaway: "Encapsulation means private fields with controlled methods, so the class enforces its own rules in one place and invalid state can never be created."
Inheritance and polymorphism: same workflow, different steps
Now the second pillar, inheritance, and its payoff, polymorphism.
Here is the real scenario. A checkout must process UPI payments and card payments. The steps differ; the workflow is identical. So put the shared part in a parent, and force each child to fill in its own difference:
// Run with: java Payments.java (one file, several classes -- fine)
public class Payments {
// THE POLYMORPHISM PAYOFF: one loop that handles every payment kind
// that exists now -- and every kind anyone adds later. This method
// never changes again.
static void processAll(Payment[] batch) {
for (Payment p : batch) {
p.process(); // the object's REAL type decides which execute() runs
}
}
public static void main(String[] args) {
Payment[] batch = {
new UpiPayment("asha@upi", 500.0),
new CardPayment("4242", 250000.0)
};
processAll(batch);
// Processing 500.0 via UpiPayment
// -> success
// Processing 250000.0 via CardPayment
// -> declined
}
}
// abstract class: can't be `new`ed itself -- exists to be extended.
abstract class Payment {
protected final double amount; // protected: children may read it
Payment(double amount) { this.amount = amount; }
abstract boolean execute(); // each child MUST provide this
void process() { // shared workflow, written ONCE
System.out.println("Processing " + amount + " via "
+ getClass().getSimpleName());
System.out.println(execute() ? " -> success" : " -> declined");
}
}
class UpiPayment extends Payment { // extends = inherits from
private final String vpa;
UpiPayment(String vpa, double amount) {
super(amount); // run the parent's constructor first
this.vpa = vpa;
}
@Override boolean execute() { return vpa.contains("@"); }
}
class CardPayment extends Payment {
private final String last4;
CardPayment(String last4, double amount) {
super(amount);
this.last4 = last4;
}
@Override boolean execute() { return amount <= 100000; } // limit check
}
execute() slot, and the object's runtime type picks which one runs.Picture it: declared type versus object type
The setup: A variable declared as the parent type holds a child object, and the code calls a method on it.
Payment p = new UpiPayment("asha@upi", 500.0); // declared: Payment, real: UpiPayment
p.process();
// p.vpa; // ❌ TRAP: Payment has no field vpa
CardPayment c = (CardPayment) p; // ❌ TRAP: p is really a UpiPayment
Make the invisible visible: The heap object is a UpiPayment carrying the fields of both layers, and the variable only sees the Payment part.
STACK HEAP
p ●-----------------------> [ UpiPayment object
(declared type: Payment) class = UpiPayment <-- the REAL type, fixed at new
amount = 500.0 <-- field from Payment
vpa ●--> "asha@upi" <-- field from UpiPayment ]
The trace: The compiler checks the declared type, and the JVM then dispatches on the real type.
p.process()
1. compiler: does Payment have process()? yes ✓ compiles
2. JVM: real class is UpiPayment, no override, so run Payment.process() ✓
3. inside process(): execute() -> real class again -> UpiPayment.execute() ✓
p.vpa
4. compiler: does Payment have vpa? no ✗ compile error
(CardPayment) p
5. JVM: is the real object a CardPayment? no, it is a UpiPayment ✗ ClassCastException
What you see: One line of output from the polymorphic call, one compile error, and one runtime error.
Processing 500.0 via UpiPayment
-> success
error: cannot find symbol // for p.vpa, symbol: variable vpa
Exception in thread "main" java.lang.ClassCastException: class UpiPayment cannot be cast to class CardPayment
// (the real message continues with module and class loader details)
Why: The declared type is a compile-time promise about what you may call, while the real type is a runtime fact that chooses which override runs.
The fix: Call only what the parent promises, and test the real type before casting.
p.process(); // ✅ FIX: use the parent's contract
if (p instanceof CardPayment c) { // ✅ FIX: check the real type first
System.out.println("limit check for " + c);
}
What you see now: The call still works and the guarded cast is simply skipped.
Processing 500.0 via UpiPayment
-> success
Interfaces and abstract classes: two ways to share
Two more shapes complete the toolkit. An interface is a pure contract —
method signatures with no state — and a class may implement many of them, whereas it
can extend only one class. Declare
interface Refundable { void refund(double amount); }, add
implements Refundable to CardPayment, and any code can now ask
"is this refundable?" without caring what class it is. The honest comparison:
| Question | Abstract class | Interface |
|---|---|---|
| Can hold state (fields)? | Yes — amount lived there | No instance state (only constants) |
| Can share method code? | Yes — process() written once | Yes, via default methods — but no state to lean on |
| How many can one class take? | Extend exactly one | Implement many |
| Constructor? | Yes (children call super(...)) | No |
| Choose when… | Related classes share state + workflow ("is-a" with common machinery) | Unrelated classes share only a capability ("can-do": Comparable, Refundable) |
Picture it: what an interface and an abstract class allow
The setup: One interface added to CardPayment, then four lines that try to use the types.
interface Refundable { void refund(double amount); }
class CardPayment extends Payment implements Refundable {
// ... fields and execute() as before ...
public void refund(double amount) { System.out.println("refunded " + amount); }
}
Refundable r1 = new CardPayment("4242", 100.0);
Refundable r2 = new UpiPayment("a@upi", 5.0);
Payment p1 = new Payment(10.0);
- Works:
Refundable r1 = new CardPayment("4242", 100.0);, becauseCardPaymentimplements the interface. - Fails:
Refundable r2 = new UpiPayment("a@upi", 5.0);, with the compile errorincompatible types: UpiPayment cannot be converted to Refundable. - Fails:
new Payment(10.0), with the compile errorPayment is abstract; cannot be instantiated.
Records: for the classes that are only data
Finally, modern Java's gift to data: the record.
Half of real-world classes exist only to carry values. Writing the constructor, getters,
equals, hashCode and toString by hand for each is
exactly the boilerplate Java was mocked for.
A record generates all five from one line:
// Run with: java Records.java (records need Java 16+; you have 21)
public class Records {
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p.x() + ", " + p.y()); // 3, 4 -- accessors, not getX()
System.out.println(p); // Point[x=3, y=4]
System.out.println(p.equals(new Point(3, 4))); // true -- VALUE equality, free
Book b = new Book("978-0134685991", "Effective Java");
System.out.println(b.title()); // Effective Java
// new Book("978-1", ""); // would throw -- validation still possible
}
}
record Point(int x, int y) { } // constructor, accessors, equals,
// hashCode, toString: ALL generated
record Book(String isbn, String title) {
Book { // compact constructor: validate, then store
if (title.isBlank()) throw new IllegalArgumentException("title required");
}
}
Picture it: what a record generates
Make the invisible visible: The one-line record Point(int x, int y) { } expands to roughly this class.
final class Point extends java.lang.Record {
private final int x;
private final int y;
Point(int x, int y) { this.x = x; this.y = y; }
public int x() { return x; }
public int y() { return y; }
public boolean equals(Object o) { /* same class and x == x and y == y */ }
public int hashCode() { /* combines x and y */ }
public String toString() { return "Point[x=" + x + ", y=" + y + "]"; }
}
The trace: The table runs the same two lines against a hand-written class with no equals and against the record.
| Code line | Plain class (no overrides) | Record |
|---|---|---|
new Pt(3, 4).equals(new Pt(3, 4)) | Silently wrong: false (compares arrows) | Works: true (compares fields) |
System.out.println(p) | Silently unhelpful: Pt@ plus a hex hash | Works: Point[x=3, y=4] |
p.x from another class | Compile error if the field is private | Compile error: the field is private, use p.x() |
The design rule this track lives by: records for data that just is,
classes for data with rules and behavior, inheritance only when several classes genuinely
share workflow. A Book is a record. A Library that enforces
"can't issue an already-issued book" is a class. Payment kinds sharing one processing
pipeline justify a hierarchy. Reaching for inheritance first is the classic fresher
over-engineering move — now you know the ordering.
- Interview takeaway: "Polymorphism: the declared type decides what I may call at compile time, and the object's real type decides which override runs at runtime. A record is a class whose constructor, accessors,
equals,hashCodeandtoStringare generated from its components."
The variable's declared type and the object's real type disagree below. Which
execute() runs — and would p.vpa compile?
Payment p = new UpiPayment("x", 500.0); // left side: Payment. right side: Upi.
p.process();
Reveal the answer
UpiPayment's — it prints "declined", because "x" contains no
@. The rule: the declared type controls what you may call
(only Payment's methods — so p.vpa doesn't compile; the compiler can't
promise every Payment has a vpa), while the runtime type controls what actually
runs. Compile-time checks the contract; runtime picks the implementation. That
one sentence is polymorphism, and it's the answer interviewers are fishing for.
Quick reference — Objects and the four pillars
- class / object
- A class is the template. An object is one filled-in copy of it.
- encapsulation
privatefields plus getters are not bureaucracy. They are a single choke point for every rule about that data.- inheritance
- Put the shared part in a parent, force each child to fill in its own difference.
- polymorphism
- One call site, many behaviours. The object decides which code runs, not the caller.
- abstract class vs interface
- Abstract class: shared state and shared code, extend exactly one. Interface: a capability with no state, implement as many as you like. Full comparison in the decision table above.
- record
- A short way to declare a class that is only data. The compiler writes the constructor, accessors,
equals,hashCodeandtoStringfor you.
07 · Core JavaCollections — The Data Structures You'll Use Every Day
Arrays cannot grow, so Java ships a library of containers that can. Three of them — list, map, set — cover most of the code you will ever write.
The three containers that cover most working code
Arrays can't grow — promised payoff time. The collections framework is Java's library of growable containers. Three of them cover most working code.
| Type | What it holds | Speed of the thing you do most |
|---|---|---|
ArrayList | An ordered, growable list. | Reading by position is instant. |
HashMap | Key → value lookup. | O(1) — effectively instant, whatever the size. |
HashSet | Membership and uniqueness. Duplicates collapse silently. | O(1) for "is this in there?" |
Generics: the brackets that keep types honest
Now the angle brackets you see everywhere, as in List<String>. Those are
generics — the brackets that keep types honest.
They tell the compiler "this list holds Strings, only Strings". Two things follow.
list.add(42) fails at compile time rather than at 3am, and nothing you take out
needs a cast.
One consequence catches every beginner: collections hold only objects, so
List<int> is illegal. You write List<Integer> instead.
That is the payoff of the wrapper types from section 03.
Picture it: what generics become after the compiler is done
The setup: A typed list, then the same list reached through a raw alias that sneaks in the wrong type.
List<String> names = new ArrayList<>();
names.add("Asha");
// names.add(42); // ❌ TRAP caught at compile time
List raw = names; // raw type: the checks are switched off
raw.add(42); // ❌ TRAP: compiles with a warning
String first = names.get(1); // crashes here, far from the bad add
Make the invisible visible: The generic types are erased, and the compiler inserts a cast wherever you read a value out.
List names = new ArrayList();
names.add("Asha");
String first = (String) names.get(0); // cast inserted by the compiler
The trace: Typed code fails at the add line, and the raw alias defers the failure to the read.
names.add(42) compiler: is int a String? no ✗ compile error
raw.add(42) raw type, no check; list now holds [Asha, 42] ✗ bad data inside
names.get(1) inserted cast (String) on an Integer ✗ ClassCastException
What you see: The compiler names the mismatch when it can, and the JVM names the failing cast when it cannot.
error: incompatible types: int cannot be converted to String
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String
// (the real message continues with module details)
Why: Generics are a compile-time check only, so avoiding raw types keeps every bad add a compile error instead of a 3am crash.
ArrayList is the default when neither says otherwise.// Run with: java CollectionsTour.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CollectionsTour {
public static void main(String[] args) {
// ArrayList: the growable array you wanted three sections ago.
// Declare as the INTERFACE (List) -- code to contracts, section 06.
List<String> titles = new ArrayList<>();
titles.add("Clean Code");
titles.add("Effective Java");
titles.add("Clean Code"); // duplicates: fine
System.out.println(titles.size()); // 3 -- size() is a METHOD
System.out.println(titles.get(1)); // Effective Java
// HashMap: key -> value, O(1) lookup however large it grows
Map<String, Integer> stock = new HashMap<>();
stock.put("978-0134685991", 3);
stock.put("978-0132350884", 0);
System.out.println(stock.get("978-0134685991")); // 3
System.out.println(stock.getOrDefault("nope", 0)); // 0 -- no crash
// HashSet: membership + uniqueness; duplicates silently collapse
Set<String> issued = new HashSet<>();
issued.add("978-0134685991");
issued.add("978-0134685991");
System.out.println(issued.size()); // 1
System.out.println(issued.contains("978-0132350884")); // false
// Iteration: enhanced-for works on every collection...
for (String t : titles) System.out.println(" " + t);
// ...and on maps via keySet()/entrySet(). NOTE: HashMap promises
// NO order -- it trades order for speed. Need order? LinkedHashMap.
for (String isbn : stock.keySet()) {
System.out.println(isbn + " -> " + stock.get(isbn)); // order may vary
}
// A first taste of STREAMS -- the modern idiom: describe WHAT,
// let the library do the HOW. Read it left to right like a sentence.
List<String> loud = titles.stream()
.filter(t -> t.startsWith("C")) // keep matching items
.map(String::toUpperCase) // transform each
.toList(); // collect the results
System.out.println(loud); // [CLEAN CODE, CLEAN CODE]
// The same thing as a loop -- identical result, more moving parts:
List<String> loud2 = new ArrayList<>();
for (String t : titles) {
if (t.startsWith("C")) loud2.add(t.toUpperCase());
}
System.out.println(loud2.equals(loud)); // true
}
}
Picture it: an ArrayList is an array with spare room
The setup: The titles list from CollectionsTour.java after three adds.
List<String> titles = new ArrayList<>();
titles.add("Clean Code");
titles.add("Effective Java");
titles.add("Clean Code");
Make the invisible visible: The list object holds a size and an arrow to a backing array that is longer than the number of elements.
STACK HEAP
titles ●-----------> [ ArrayList size = 3 ]
elementData ●---> [ ● | ● | ● | _ | _ | _ | _ | _ | _ | _ ]
capacity 10 each ● aims at a String
The trace: When the array is full, an add allocates a bigger one and copies the arrows across.
first add empty list gets a backing array of 10 ✓
adds 2..10 write into the next free slot ✓
add the 11th array full: new array of 15 (10 + 10/2) ✗ must grow
copy 10 arrows, write the 11th, size = 11 ✓
capacities over time 10 -> 15 -> 22 -> 33 -> ...
Why: Growing by about half each time keeps adds cheap on average, and reading by position is one array lookup.
Picture it: a HashMap is an array of buckets
The setup: The stock map from CollectionsTour.java, plus one more key.
Map<String, Integer> stock = new HashMap<>();
stock.put("978-0134685991", 3);
stock.put("978-0132350884", 0);
stock.put("978-1111111111", 7);
System.out.println(stock.get("978-0132350884"));
Make the invisible visible: The map is a table of 16 buckets by default, and each key's hash picks a bucket.
# illustrative: real bucket numbers depend on each key's hashCode
table (16 buckets)
[ 0] -> null
[ 3] -> ("978-0134685991" = 3)
[ 9] -> ("978-0132350884" = 0) -> ("978-1111111111" = 7) <-- two keys, one bucket: a chain
[15] -> null
The trace: A lookup hashes the key, jumps to one bucket and compares only the few entries in it.
stock.get("978-0132350884")
1. key.hashCode(), mixed, then index = (16 - 1) & hash -> bucket 9 ✓
2. first entry in bucket 9: equals("978-0132350884")? no ✗ next
3. second entry: equals? yes ✓ return 0
resize: when entries exceed 12 (0.75 x 16), the table doubles to 32
long chain: a bucket with 8+ entries (table at least 64) becomes a tree
What you see: The value comes back after at most a short walk.
0
Why: Hashing spreads keys over many buckets, so each bucket stays short and a lookup does not depend on the map's size. A HashSet is built on a HashMap using the elements as keys.
Picture it: a key class with equals but no hashCode
The setup: A key type that overrides only equals.
class Isbn {
final String v;
Isbn(String v) { this.v = v; }
@Override public boolean equals(Object o) { // ❌ TRAP: hashCode not overridden
return o instanceof Isbn i && i.v.equals(v);
}
}
Map<Isbn, Integer> m = new HashMap<>();
m.put(new Isbn("X"), 3);
System.out.println(m.get(new Isbn("X")));
Make the invisible visible: Two equal keys inherit identity-based hash codes, so they normally land in different buckets.
# illustrative
[ 4] -> (Isbn@1b6d, "X" = 3) <-- put used the first object's hash
[11] -> null <-- get looks here for the second object: nothing
What you see: The lookup misses even though equals says the keys match.
null
Why: HashMap finds the bucket from hashCode first and only then calls equals, so equal objects must have equal hash codes.
The fix: Override hashCode alongside equals, or make the key a record.
@Override public int hashCode() { return v.hashCode(); } // ✅ FIX
// or: record Isbn(String v) { } // ✅ FIX: generated for you
What you see now: Both keys land in the same bucket and match.
3
Picture it: unboxing a missing map value
The setup: Reading a missing key into an int.
int n = stock.get("nope"); // ❌ TRAP: get returns null for a missing key
Make the invisible visible: The assignment hides a method call on whatever get returned.
int n = stock.get("nope").intValue(); // intValue() on null
What you see: A NullPointerException at that line (the exact message text varies by JDK version).
Exception in thread "main" java.lang.NullPointerException
at CollectionsTour.main(CollectionsTour.java:21)
The fix: Give the map a default for missing keys.
int n = stock.getOrDefault("nope", 0); // ✅ FIX
What you see now: The default comes back and the program continues.
0
Lambdas and method references: the shapes you will see everywhere
Two reading notes on that stream, because both shapes are everywhere in modern code.
t -> t.startsWith("C")is a lambda — a tiny inline function, read as "given t, produce this".String::toUpperCaseis a method reference — shorthand for a lambda that does nothing but call one method.
Do not chase streams for their own sake yet. The loop form is equally correct, and this primer's rule is loops until comfortable, streams where they read better.
But do recognise the idiom on sight. Modern codebases are written in it, including the Claude SDK you will meet in section 12.
Picture it: what the lambda and the method reference stand for
Make the invisible visible: Both are shorthand for an object with one method, and the code below does the same job in long form.
// t -> t.startsWith("C") behaves like:
Predicate<String> keep = new Predicate<String>() {
public boolean test(String t) { return t.startsWith("C"); }
};
// String::toUpperCase behaves like the lambda: t -> t.toUpperCase()
// (the compiler actually uses invokedynamic, but the behaviour is this)
- Interview takeaway: "A
Listgrows by replacing its backing array, aHashMapfinds a key by hash thenequals, and generics are checked at compile time and erased afterwards. If I overrideequalsI must overridehashCodetoo."
Overloading (section 05) meets collections. What does this print?
import java.util.ArrayList;
import java.util.List;
public class Predict4 {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(10, 20, 30));
nums.remove(1);
System.out.println(nums);
}
}
Reveal the answer
[10, 30] — not [20, 30]. List has two removes:
remove(int index) and remove(Object value). A bare 1
is an int, so overload resolution picks remove-by-index and deletes
the element at position 1 (the 20). To remove the value 1 you'd force the object
overload: nums.remove(Integer.valueOf(1)). Overloading plus autoboxing,
conspiring — a genuinely asked interview curveball.
nums = [10 | 20 | 30] size 3
nums.remove(1) int -> remove(int index)
index 1 removed, later slots shift left: [10 | 30 | _] size 2
nums.remove(Integer.valueOf(1)) Integer -> remove(Object value)
searches for the VALUE 1, finds none, list unchanged, returns false
Quick reference — Collections
- ArrayList
- Ordered, growable list. Reading by position is instant.
- HashMap
- Key → value lookup in O(1).
- HashSet
- Membership and uniqueness in O(1). Duplicates collapse silently.
- generics
- The angle brackets.
List<String>tells the compiler this list holds Strings only, so a wrongaddfails at compile time and nothing needs a cast on the way out. - Why List<int> is illegal
- Collections hold only objects. You write
List<Integer>— which is what the wrapper types are for. - lambda / method reference
t -> t.startsWith("C")is a tiny inline function.String::toUpperCaseis shorthand for a lambda that only calls one method.
08 · Core JavaExceptions — Failing Loudly, On Purpose
An exception is how a method says "I cannot do what you asked" without returning a wrong answer. Java's distinctive choice is that the compiler forces you to handle some of them and not others.
When something goes wrong mid-method, such as a missing file or input that isn't a number,
returning a fake value like -1 just moves the bug downstream.
Java's answer is to throw an exception: an object describing the failure that abandons normal execution and travels up the call chain. It ends in one of two ways.
- Caught: some
catchblock claims it and the program carries on. - Uncaught: it reaches the top, prints the stack trace and ends the program.
You've already thrown some: IllegalArgumentException guarded
Student's marks. Now the catching side:
// Run with: java ExceptionsTour.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ExceptionsTour {
// Your own exception: NAME the domain failure, carry the context.
// Extending RuntimeException makes it unchecked (see below).
static class BookNotFoundException extends RuntimeException {
BookNotFoundException(String isbn) { super("no such book: " + isbn); }
}
static int parseMarks(String raw) {
try {
return Integer.parseInt(raw); // may throw NumberFormatException
} catch (NumberFormatException e) {
System.out.println("not a number: " + raw);
return -1;
} finally {
// finally runs on EVERY exit path -- success, catch, even return.
System.out.println("attempted: " + raw);
}
}
public static void main(String[] args) throws IOException {
System.out.println(parseMarks("78")); // attempted: 78 / then 78
System.out.println(parseMarks("many")); // not a number: many /
// attempted: many / then -1
// CHECKED exceptions: the compiler FORCES you to face these.
// Files.writeString declares `throws IOException`, so this method
// must either catch it or declare it too (main does, above).
Path notes = Path.of("notes.txt");
Files.writeString(notes, "Java exceptions, day one\n");
// try-with-resources: whatever you open in ( ) is CLOSED for you,
// even if the body blows up mid-read. Use it for every file/socket.
try (var reader = Files.newBufferedReader(notes)) {
System.out.println(reader.readLine()); // Java exceptions, day one
}
Files.delete(notes); // tidy up the demo file
// UNCHECKED exceptions (RuntimeException family): the compiler
// stays silent -- these usually mean "programming bug or bad input".
try {
throw new BookNotFoundException("978-000");
} catch (BookNotFoundException e) {
System.out.println(e.getMessage()); // no such book: 978-000
}
}
}
Picture it: an exception climbs the call stack
The setup: Three methods call each other, and the innermost one is given text that is not a number.
public class Climb {
static int parse(String raw) { return Integer.parseInt(raw); }
static int load(String raw) { return parse(raw) * 2; }
public static void main(String[] args) {
System.out.println(load("many")); // ❌ TRAP: nobody catches
System.out.println("never printed");
}
}
Make the invisible visible: Each call adds a frame to the stack, and the exception leaves them from the top downward.
CALL STACK (top is running now)
+--------------------------------+
| Integer.parseInt("many") | throws NumberFormatException here
| Climb.parse | no catch: frame discarded
| Climb.load | no catch: frame discarded
| Climb.main | no catch: frame discarded
+--------------------------------+
| JVM: prints the stack trace, the thread ends |
The trace: The exception is passed to each caller in turn until something catches it or the stack runs out.
parseInt throws NumberFormatException ✗
parse has a catch for it? no ✗ unwind
load has a catch for it? no ✗ unwind
main has a catch for it? no ✗ unwind, uncaught
JVM prints the trace, "never printed" is skipped
What you see: The trace lists the frames from the innermost call to main.
# illustrative output (line numbers vary)
Exception in thread "main" java.lang.NumberFormatException: For input string: "many"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:661)
at Climb.parse(Climb.java:2)
at Climb.load(Climb.java:3)
at Climb.main(Climb.java:6)
Why: An exception keeps leaving frames until a matching catch is found, and the stack trace is the list of frames it left.
The fix: Catch it in the method that knows what to do, here main.
try {
System.out.println(load("many"));
} catch (NumberFormatException e) { // ✅ FIX: the climb stops here
System.out.println("bad input: " + e.getMessage());
}
System.out.println("still running");
What you see now: The message prints and the program carries on.
bad input: For input string: "many"
still running
Picture it: when finally runs and what try-with-resources expands to
The trace: Follow parseMarks("many") from ExceptionsTour.java, where the catch returns -1.
parseMarks("many")
1. try: Integer.parseInt("many") throws ✗
2. catch NumberFormatException: prints "not a number: many", return value -1 is set aside
3. finally runs BEFORE the method really returns: prints "attempted: many" ✓
4. method returns -1 ✓
What you see: The two messages come first and the returned value is printed by the caller last.
not a number: many
attempted: many
-1
Make the invisible visible: try-with-resources is roughly a try with a finally that closes the resource.
var reader = Files.newBufferedReader(notes);
try {
System.out.println(reader.readLine());
} finally {
reader.close(); // runs on success and on exception
}
// (the real expansion also handles an exception thrown by close() itself)
The distinctive Java choice — and a guaranteed interview topic — is the checked versus unchecked split.
Checked exceptions (IOException and friends) are part of a
method's signature. Callers must either catch them or re-declare them, and the compiler
enforces it. The intent was noble: external failures like a missing file will happen,
so force every caller to have a plan.
Picture it: what the compiler demands for a checked exception
The setup: The Files.writeString call from ExceptionsTour.java, in a method that does not declare IOException.
static void save(Path notes) {
Files.writeString(notes, "day one\n"); // ❌ TRAP: declares throws IOException
}
- Fails: the call above, with the compile error
unreported exception IOException; must be caught or declared to be thrown. - Works: adding
throws IOExceptiontosave, so the caller must deal with it. - Works: wrapping the call in
try { ... } catch (IOException e) { ... }with a real plan in the catch.
Make the invisible visible: The worst response to that compile error is an empty catch, which makes the failure invisible at runtime.
try {
Files.writeString(notes, "day one\n");
} catch (IOException e) {
// ❌ TRAP: swallowed, nobody ever learns the write failed
}
What you see: On a read-only disk the program prints nothing and carries on as if the file existed.
(no output, no trace, and notes.txt was never written)
The fix: Rethrow as an unchecked exception that keeps the original as its cause.
} catch (IOException e) {
throw new UncheckedIOException(e); // ✅ FIX: loud, with the cause attached
}
What you see now: The failure surfaces with a stack trace.
Exception in thread "main" java.io.UncheckedIOException: java.io.IOException: ...
// "Caused by: java.io.IOException" follows, naming the real problem
The honest assessment is that this is a genuinely contested design, and you should be able to argue both sides. Two criticisms carry the most weight:
- Forced handling breeds empty
catchblocks that swallow errors silently — which is worse than crashing, because now the failure is invisible. - No major language since has copied the feature. Not C#, not Kotlin, not Python. Even large Java frameworks like Spring systematically wrap checked exceptions into unchecked ones.
The working rule of thumb: checked for recoverable external conditions when an API forces them on you, unchecked for bugs and invalid arguments. When in doubt, modern Java leans unchecked.
Say it that way — as a trade-off, not as dogma — and you will sound like the second pile of candidates.
- Interview takeaway: "An exception unwinds the call stack frame by frame until a matching catch, and
finallyruns on every exit path. Checked exceptions must be caught or declared, unchecked ones need not, and I never swallow one with an empty catch."
Quick reference — Exceptions
- checked
- Part of the method signature. The compiler forces every caller to catch it or re-declare it.
IOExceptionand friends. - unchecked
- No compiler enforcement. Bugs and invalid arguments.
- The rule of thumb
- Checked for recoverable external conditions an API forces on you. Unchecked for bugs. When in doubt, modern Java leans unchecked.
- Why it's contested
- Forced handling breeds empty
catchblocks that hide failures, and no major language since has copied the feature. Say it as a trade-off, not as dogma.
09 · ToolingMaven, Gradle, JARs, and IDEs in One Page
Real projects have hundreds of files and dozens of libraries, so nobody runs
java File.java at work. A build tool fetches your dependencies and produces one
runnable artefact.
Everything so far ran with java File.java. That was deliberate, so the
language never hid behind tooling.
But real projects have hundreds of files and dozens of external libraries. That is the problem build tools solve. Maven and Gradle do two jobs.
- Dependency management. You name a library and a version in a manifest —
pom.xmlfor Maven,build.gradlefor Gradle — and the tool downloads it, plus everything it needs, and so on down the chain. - Reproducible builds. Compile, test and package with one command, and get an identical result on your laptop and on the build server.
If you have seen a package manager in any other ecosystem, this is that same idea. If you have not, the mental model is a shopping list that the tool goes and fills for you.
A JAR is where a build ends up. It is a zip file of compiled
.class files plus a manifest, and it is the unit you hand to a server to run.
# You already own these -- they shipped inside the JDK:
javac Hello.java # compile: .java -> .class bytecode
java Hello # run a compiled class (note: no extension)
java Hello.java # compile-and-run in one step -- this whole primer
# Packaging for shipping: a JAR is a zip of .class files + manifest
jar --create --file app.jar --main-class Hello Hello.class
java -jar app.jar # runs anywhere a JVM exists
Picture it: what a build tool fetches and what a JAR holds
Make the invisible visible: You name one library in the manifest, and the tool also fetches whatever that library needs.
# illustrative: library names are placeholders
your-app
+-- library-a 2.1 (you listed this)
| +-- library-b 1.4 (you did NOT list this: fetched for you)
+-- library-c 5.0 (you listed this)
+-- library-b 1.4 (shared: fetched once)
The trace: One command runs the build stages in order and stops at the first failure.
mvn package
1. compile .java -> .class ✓
2. test run the unit tests ✓ (a failing test stops here ✗, no JAR)
3. package zip .class files + manifest -> app.jar ✓
What you see: Listing the JAR shows a plain zip of class files plus the manifest.
$ jar tf app.jar
META-INF/
META-INF/MANIFEST.MF
Hello.class
$ unzip -p app.jar META-INF/MANIFEST.MF
Manifest-Version: 1.0
Main-Class: Hello
Why: The manifest's Main-Class line tells java -jar which class's main to start.
- Interview takeaway: "Maven and Gradle manage dependencies, including the transitive ones, and give a reproducible build. A JAR is a zip of compiled classes plus a manifest, and
java -jarruns the class named in itsMain-Class."
On IDEs: IntelliJ IDEA Community Edition (free) is the industry default for Java, and once you're past this primer you should absolutely use it — the red squiggles, auto-imports, and refactoring tools are a second teacher. This primer stays IDE-free on purpose: single files and a terminal keep you honest about what the language does versus what the IDE does for you, and interviewers notice the difference. Learn the language bare, then accept the comforts.
There are no dumb questions
- Is Java dying? My seniors say everything new is Python or JavaScript.
- No — it's just not fashionable, which is a different thing. Java runs a staggering share of enterprise back-ends (banking, telecom, retail, government), sits consistently in the top handful of every index of language use, and the biggest fresher hiring pipelines in the Indian market interview on it specifically. New startups may not pick it; the companies that hire thousands of freshers a year already did, decades ago, and their systems aren't going anywhere. "Boring and everywhere" is a career floor, not a ceiling.
- Why is Java so wordy compared to other languages?
- Partly age, partly philosophy: Java makes you declare intent (types, visibility,
exceptions) so the compiler can catch mistakes and so code reads unambiguously
at 3 a.m. in a codebase with four hundred contributors. Modern Java has shed real
weight —
var, records, arrow switch — and what's left is mostly deliberate. You'll be slower to write and faster to debug; enterprises take that trade every time. - My college teaches Java 8. Have I learned the wrong thing?
- No — perhaps 90% of this primer is identical on Java 8, and plenty of banks still run
it. The specifically modern pieces here are
var(Java 10), arrow switch (14), records (16), and single-filejava File.javaexecution (11). Know which is which and you can flex either way — mentioning "records replaced the getter boilerplate from Java 8" in an interview is a currency signal that costs one sentence. - Do I need Spring before applying for jobs?
- Not for fresher rounds — they test core Java: OOP pillars, collections, strings, exceptions, exactly this primer's contents. Spring (the dominant enterprise framework) matters from your first job onward, and learning it before the fundamentals is how people end up able to annotate but not explain. Core first; Spring is a two-week ramp once the core is solid.
- Should I do my DSA practice in Java?
- It's a fine choice — most Indian interview prep material is written in it, and the
collections framework maps directly onto DSA vocabulary:
ArrayList≈ dynamic array,HashMap≈ hash table,ArrayDeque≈ stack/queue. If your other language is Python, doing DSA in Java doubles your practice in the language enterprises will interview you in anyway.
Quick reference — Build tooling
- Maven / Gradle
- Two jobs: fetch your dependencies (and their dependencies), and produce the same build on your laptop and the build server.
- pom.xml / build.gradle
- The manifest where you name a library and a version. Maven and Gradle respectively.
- JAR
- A zip of compiled
.classfiles plus a manifest. The unit you hand a server to run.
10 · Watch it breakThe Fresher-Classic Gotchas, Demonstrated
Five bugs that catch nearly every beginner, each one run in front of you rather than described. Meeting them here is cheaper than meeting them in an interview.
Every block below compiles, runs, and quietly does something other than what it looks like it does. These six are the canonical Java traps.
Each one is both a real bug you'll write and a screening question you'll be asked. Run the file, watch it lie, and you're inoculated on both fronts.
Almost all of them trace to one fact you now own: object variables hold arrows, not
objects — so == compares arrows.
// Run with: java Gotchas.java
import java.util.ArrayList;
import java.util.List;
public class Gotchas {
public static void main(String[] args) {
// GOTCHA 1 -- == on Strings compares REFERENCES (arrows), not text
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b); // true -- wait, what? see the pool note
System.out.println(a == c); // false -- `new` forced a fresh object
System.out.println(a.equals(c)); // true -- .equals compares characters
// The wrinkle: identical LITERALS are interned in a "string pool",
// so a and b share one object -- which makes == succeed just often
// enough in testing to ship the bug. Rule: == for primitives,
// .equals for objects. No exceptions worth learning.
// GOTCHA 2 -- the Integer cache makes == lie convincingly
Integer small1 = 127, small2 = 127;
Integer big1 = 128, big2 = 128;
System.out.println(small1 == small2); // true -- -128..127 are cached
System.out.println(big1 == big2); // false -- 128 isn't: two objects
System.out.println(big1.equals(big2)); // true -- as always
// Same disease as gotcha 1: == compared arrows; the cache just makes
// small values share one object. Tests with small numbers pass,
// production with big numbers fails. Chef's kiss of a bug.
// GOTCHA 3 -- integer division truncates, silently
System.out.println(5 / 2); // 2 -- not 2.5
System.out.println(5 % 2); // 1 -- % is the remainder
System.out.println(5 / 2.0); // 2.5 -- one double rescues the math
// GOTCHA 4 -- NullPointerException: the billion-dollar mistake, live.
// A reference holding NOTHING; calling anything through it explodes.
String title = null;
try {
title.length();
} catch (NullPointerException e) {
System.out.println("NPE: called length() on null");
}
// Defensive habits: never return null when an empty list will do;
// check at boundaries; fail fast with a clear message.
// (java.util.Optional is the standard library's structured answer --
// file it under "further reading", not fresher-round material.)
// GOTCHA 5 -- mutating a list WHILE looping over it
List<String> lent = new ArrayList<>(List.of("b1", "b2", "b3"));
try {
for (String s : lent) {
if (s.equals("b1")) lent.remove(s); // rug-pull under the iterator
}
} catch (java.util.ConcurrentModificationException e) {
System.out.println("CME: the iterator noticed the list changed");
}
lent.removeIf(s -> s.equals("b1")); // the safe idiom
System.out.println(lent); // [b2, b3]
// (Cursed trivia: removing the second-to-last element can sneak past
// the check entirely. Never rely on it -- use removeIf or an Iterator.)
// GOTCHA 6 -- array vs ArrayList: different species, different grammar
int[] arr = {1, 2, 3};
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
System.out.println(arr.length + " " + list.size()); // 3 3 -- field vs method
System.out.println(list); // [1, 2, 3]
System.out.println(arr); // [I@1b6d3586 -- your hex will vary!
// Arrays never got a friendly toString. Use java.util.Arrays.toString(arr).
list.add(4); // lists grow
// arr[3] = 4; // arrays crash: ArrayIndexOutOfBoundsException
}
}
The six gotchas, one at a time
The file above printed the answers. Below, each trap gets the same steps: the setup, a picture of what is really in memory, a trace, the evidence, the reason, and the fix.
Gotcha 1: == on Strings
The setup: three variables hold the text "hello", but only two of them share one object.
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b); // Result: true (same pooled object)
System.out.println(a == c); // ❌ TRAP: false (new forced a second object)
System.out.println(a.equals(c)); // Result: true (same characters)
Make the invisible visible: the pool holds one "hello"; new builds another one outside it.
STACK (main's frame) HEAP
a ----------+ +------------------------------+
+-----------> | string pool: "hello" | one object
b ----------+ +------------------------------+
c ----------------------> | String "hello" (made by new) | a second object
+------------------------------+
The trace: each line asks a different question of the same three arrows.
a == b same arrow? both point at the pooled object ✓ true
a == c same arrow? pooled object vs the object new made ✗ false
a.equals(c) same text? h-e-l-l-o vs h-e-l-l-o ✓ true
What you see: the console prints three lines.
true
false
true
Why: == on objects compares arrows. Identical literals are interned in the pool, so they share one object, while new always allocates another.
The fix: compare text with .equals(), even for a String built at runtime.
String d = new StringBuilder("hel").append("lo").toString(); // built at runtime, like user input
System.out.println(a.equals(b)); // ✅ FIX: true
System.out.println(a.equals(c)); // ✅ FIX: true
System.out.println(a.equals(d)); // ✅ FIX: true (a == d would print false: d is outside the pool)
What you see now: the same three-line layout, and every line is true.
true
true
true
The wrinkle interviewers love is that "hello" == "hello" is true.
The bug therefore passes your tests.
Then a String built at runtime arrives outside the pool: user input, a file read, or
new String. Equality silently fails.
Bugs that pass tests are the expensive kind. The .equals() habit costs nothing, so
install it now.
- Interview takeaway: Literals share one pooled object, so
==passes in tests. Runtime strings sit outside the pool, so I always use.equals()for text.
Gotcha 2: the Integer cache
The setup: two pairs of boxed Integers, one pair at 127 and one at 128.
Integer small1 = 127, small2 = 127;
Integer big1 = 128, big2 = 128;
System.out.println(small1 == small2); // Result: true (-128..127 are cached)
System.out.println(big1 == big2); // ❌ TRAP: false (128 is not cached: two objects)
System.out.println(big1.equals(big2)); // Result: true
Make the invisible visible: the compiler inserted a method call you never wrote, and that call decides whether objects are shared.
Integer small1 = Integer.valueOf(127); // inside -128..127: returns the shared cached object
Integer big1 = Integer.valueOf(128); // outside the cache: a fresh Integer object each call
STACK HEAP
small1 --+ +-----------------------+
small2 --+------------> | Integer 127 (cached) | one shared object
+-----------------------+
big1 --------------> | Integer 128 |
big2 --------------> | Integer 128 | two separate objects
+-----------------------+
The trace: one line per comparison.
small1 == small2 same arrow? both point at the cached 127 ✓ true
big1 == big2 same arrow? two different Integer objects ✗ false
big1.equals(big2) same value? 128 and 128 ✓ true
What you see: the console prints three lines.
true
false
true
Why: == compared arrows again, and the cache only makes small values share an object. Tests with small numbers pass, and production with big numbers fails.
The fix: compare values, never arrows.
System.out.println(small1.equals(small2)); // ✅ FIX: true
System.out.println(big1.equals(big2)); // ✅ FIX: true
System.out.println(big1.intValue() == big2.intValue()); // ✅ FIX: true (two primitives, compared by value)
What you see now: all three lines are true.
true
true
true
- Interview takeaway: Autoboxing calls
Integer.valueOf, which caches -128 to 127. Comparing boxed values with==compares arrows, so I use.equals().
Gotcha 3: integer division
The setup: three divisions that look like the same arithmetic.
System.out.println(5 / 2); // ❌ TRAP: 2 (both operands are int)
System.out.println(5 % 2); // Result: 1 (the remainder)
System.out.println(5 / 2.0); // ✅ FIX: 2.5 (one double rescues the math)
The trace: the type of the operands decides the kind of division.
5 / 2 int / int -> integer division, fraction dropped ✗ 2 (not 2.5)
5 % 2 remainder of 5 / 2 ✓ 1
5 / 2.0 int / double -> 5 widened to 5.0, then 5.0 / 2.0 ✓ 2.5
What you see: the console prints three lines.
2
1
2.5
Why: when both operands are int, the result is an int and the fraction is thrown away without any warning.
The fix: make one operand a double before dividing, not after.
int a = 5, b = 2;
System.out.println(a / b); // ❌ TRAP: 2
System.out.println((double) a / b); // ✅ FIX: 2.5 (cast first, then divide)
System.out.println((double) (a / b)); // ❌ TRAP: 2.0 (divided as ints, cast too late)
What you see now: the middle line is the fix.
2
2.5
2.0
- Interview takeaway:
int / intis integer division and silently drops the fraction. I make one operand adoublebefore the division happens.
Gotcha 4: NullPointerException
The setup: a reference variable that holds nothing, and a method call through it.
String title = null;
title.length(); // ❌ TRAP: follows an arrow that does not exist
Make the invisible visible: the variable is a stack slot holding null, so there is no object on the heap to call.
STACK HEAP
title [ null ] (no object: nothing to follow)
title.length() means "follow the arrow, then run length() on the object"
^ the arrow leads nowhere
The trace: declaring the variable is legal, and the call is where it breaks.
String title = null; slot holds null, not an arrow ✓ legal
title.length() follow the arrow to the object ... ✗ no object: NullPointerException
What you see: an uncaught NPE ends the thread with a stack trace whose top line points at your call.
# illustrative output
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "String.length()" because "title" is null
at Gotchas.main(Gotchas.java:54)
# the quoted variable name needs javac -g; without it the message shows a slot name such as "<local1>"
Why: a null reference points at nothing, and any call through it fails at that exact line.
The fix: fail fast where the null enters, with a message that names the problem.
import java.util.Objects;
String title = null;
Objects.requireNonNull(title, "title must not be null"); // ✅ FIX: fail fast at the boundary
// Also: never return null when an empty list will do
What you see now: same kind of failure, but the message names the cause.
# illustrative output
Exception in thread "main" java.lang.NullPointerException: title must not be null
at java.base/java.util.Objects.requireNonNull(Objects.java)
at Gotchas.main(Gotchas.java:54)
- Interview takeaway: A null reference points at nothing, so calling through it throws
NullPointerException. I check at boundaries and fail fast with a clear message.
Gotcha 5: changing a list while looping over it
The setup: a for-each loop that removes an element from the very list it is walking.
List<String> lent = new ArrayList<>(List.of("b1", "b2", "b3"));
for (String s : lent) {
if (s.equals("b1")) lent.remove(s); // ❌ TRAP: rug-pull under the iterator
}
Make the invisible visible: the enhanced for loop is an iterator, and the list counts its own changes.
Iterator<String> it = lent.iterator(); // remembers expectedModCount = lent.modCount
while (it.hasNext()) {
String s = it.next(); // checks: modCount still equals expectedModCount?
if (s.equals("b1")) lent.remove(s); // list.modCount goes up; the iterator is not told
}
The trace: one line per step, with the counters spelled out (N is the starting modCount).
1 iterator created expectedModCount = N
2 next() returns "b1", cursor = 1 ✓
3 lent.remove("b1") array is [b2, b3], size = 2, modCount = N+1
4 hasNext() cursor 1 != size 2, so true ✓
5 next() modCount N+1 != expectedModCount N ✗ ConcurrentModificationException
What you see: the exception is caught in the demo, which prints one line.
CME: the iterator noticed the list changed
# uncaught, the trace top would read:
# java.util.ConcurrentModificationException
# at java.base/java.util.ArrayList$Itr.checkForComodification(...)
Why: the iterator compares counters on every next(), and your direct remove changed the list behind its back.
The fix: let the list remove for you, or remove through the iterator itself.
lent.removeIf(s -> s.equals("b1")); // ✅ FIX: the list manages its own counters
System.out.println(lent); // Result: [b2, b3]
What you see now: no exception, and the list holds the survivors.
[b2, b3]
The cursed trivia from the code comment, as a trace. Remove the second-to-last element and the loop quietly ends before the check can run:
list [b1, b2, b3], remove "b2" while standing on it
next() returns "b2", cursor = 2
remove(b2) array is [b1, b3], size = 2
hasNext() cursor 2 != size 2 is false ✗ loop ends silently; "b3" was never visited, and no exception
- Interview takeaway: The enhanced for loop uses an iterator that detects structural changes and throws
ConcurrentModificationException. I remove withremoveIfor the iterator.
Gotcha 6: array versus ArrayList
The setup: an array and a list holding the same three numbers, treated with the same habits.
int[] arr = {1, 2, 3};
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
System.out.println(arr.length + " " + list.size()); // Result: 3 3 (field vs method)
System.out.println(list); // Result: [1, 2, 3]
System.out.println(arr); // ❌ TRAP: [I@1b6d3586
arr[3] = 4; // ❌ TRAP: arrays cannot grow
Make the invisible visible: the array is the data itself, and the list is an object wrapping a hidden array of arrows.
STACK HEAP
arr ---------------> int[3] [ 1 | 2 | 3 ] fixed length, a field: arr.length
list ---------------> ArrayList { size = 3 }
elementData --> Object[ ->Integer 1 | ->Integer 2 | ->Integer 3 ]
add(4) when full: allocates a bigger Object[] and copies
What you see: the array prints its type code and hash, and the out-of-range write throws.
# illustrative output (your hex will vary)
3 3
[1, 2, 3]
[I@1b6d3586
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Why: arrays never got a friendly toString and cannot change length, while ArrayList is a real class that grows.
The fix: use Arrays.toString to print an array, and a list when you need growth.
System.out.println(java.util.Arrays.toString(arr)); // ✅ FIX: [1, 2, 3]
list.add(4); // ✅ FIX: lists grow
System.out.println(list); // Result: [1, 2, 3, 4]
What you see now: readable output, and no crash.
[1, 2, 3]
[1, 2, 3, 4]
- Interview takeaway: An array has a fixed length (
.length) and no usefultoString. AnArrayListwraps a growable array (.size()), and I print arrays withArrays.toString.
11 · Under the hoodThe JVM in One Page
You never compile or free anything by hand, because two pieces of machinery do it for you: a compiler that translates your hot code to machine code while the program runs, and a collector that reclaims objects nothing can reach any more.
Optional depth — but it is what makes the interview answers precise.
From source to machine code
When you run java Hello.java, the compiler produces bytecode,
the JVM's portable instruction set from Fig. E1.1. The JVM then starts interpreting
that bytecode, one instruction at a time.
While it interprets, it watches. It notices which methods run hot, and hands those to the JIT (just-in-time) compiler, which translates them into native machine code on the fly.
That is why long-running Java servers get faster the longer they run: the JVM is optimising your actual workload while it serves it.
Watch a method get hot
The setup: a tiny method called in a loop, so the JVM has something to notice.
public class Hot {
static int square(int x) { return x * x; }
public static void main(String[] args) {
long sum = 0;
for (int i = 0; i < 1_000_000; i++) sum += square(i); // square() becomes hot
System.out.println(sum);
}
}
The trace: the same method is run three different ways during one program.
first calls square() is INTERPRETED, one bytecode at a time (slow, but starts instantly)
counter climbs the JVM counts calls and loop passes ✓ square() is hot
past a threshold square() is queued for the quick compiler ✓ native code, tier 3 (C1)
still very hot recompiled with heavier optimisation ✓ native code, tier 4 (C2)
What you see: the flag -XX:+PrintCompilation prints one line each time the JIT compiles something.
# illustrative output
$ java -XX:+PrintCompilation Hot
41 12 3 Hot::square (4 bytes)
103 57 4 Hot::square (4 bytes)
# columns: ms since start, compile id, flags, tier, method (size). Tier 3 = C1, tier 4 = C2
The same method appears twice, which is the JIT upgrading it as it proves itself hot.
Garbage collection in three sentences
- You allocate. You
newobjects but never free them. - The collector reclaims. It periodically finds objects that no reference can reach, and frees them.
- You trade. A little runtime overhead buys immunity to an entire category of memory bugs.
You need no tuning knowledge at this level. Just the mechanism.
Stack and heap
Memory is two regions, and the split explains half this appendix retroactively.
- The stack holds one frame per method call: local variables, gone when the method returns.
- The heap holds every object.
A variable of object type is a small stack slot containing an arrow into the heap:
==, pass-by-value, and the GC have in common.Watch a frame come and go
The setup: main calls a helper and passes it the same object.
Student s = new Student("S-101"); // object on the heap, arrow in main's frame
report(s); // report gets its OWN copy of the arrow
// after report returns, its frame is gone but the Student is not
Make the invisible visible: the stack grows one frame per call and shrinks when the call returns, while the heap object stays put.
while report(x) runs after report returns
STACK HEAP STACK HEAP
+-----------------+ +-----------------+
| report: x ------+--+ | main: s --------+--+
+-----------------+ | | marks = 78| |
| main: s ------+--+--> Student +-----------------+ +--> Student
| marks=78| "S-101" "S-101"
+-----------------+ (report's frame is popped; x is gone)
What you see: a thread dump lists the frames, innermost call first.
# illustrative output
$ jcmd <pid> Thread.print
"main" #1 prio=5 ... runnable
java.lang.Thread.State: RUNNABLE
at Frames.report(Frames.java:12) <- top of the stack: the running call
at Frames.main(Frames.java:7) <- the caller waits underneath
Two variables, one object, and frames that vanish on return. That is the whole mental
model behind ==, pass-by-value and garbage collection.
See the actual bytecode — optional depth
The JDK ships a disassembler, javap. Compile Hello.java,
point it at the class, and there's your main method as the stack machine the JVM actually
executes — each line one bytecode instruction:
$ javac Hello.java
$ javap -c Hello
public static void main(java.lang.String[]);
Code:
0: getstatic #7 // Field java/lang/System.out
3: ldc #13 // String Hello, Java
5: invokevirtual #15 // Method java/io/PrintStream.println
8: return
Push the output stream, push the string constant, invoke println, return. "Java is compiled AND interpreted" stops being a memorized sentence once you've read your own bytecode — this is the artifact that travels to any OS, and the JIT's raw material.
- Interview takeaway: Source compiles once to bytecode. The JVM interprets it, and the JIT compiles hot methods to native code while the program runs. Locals live in stack frames and objects live on the heap, with arrows between them.
Quick reference — The JVM
- bytecode
- The JVM's portable instruction set.
javacproduces it once; any JVM on any OS runs those identical bytes. - JIT
- The just-in-time compiler. The JVM interprets bytecode, watches which methods run hot, and compiles those to native machine code while the program runs.
- Why servers get faster over time
- Because the JIT is optimising your real workload while it serves it.
- garbage collection
- You
newobjects and never free them. The collector finds objects no reference can reach and reclaims them.
12 · Memory & GCMemory Management — From Mechanism to Tuning
Objects are born, nearly all of them die within moments, and the few survivors get moved somewhere cheaper to ignore. Understanding that one cycle is what turns "the service pauses for two seconds" from a mystery into a checklist.
Fig. E1.5 gave you the two regions. This section is what happens to the heap over time.
It earns its own chapter because it is the interview topic that grows with you. The same subject is asked three different ways as your career moves:
- Fresher rounds ask "stack versus heap?"
- Two-years-in rounds ask "how does garbage collection actually work?"
- Enterprise ops rounds ask "the service pauses for two seconds every few minutes — what do you check first?"
The answers stack on each other in that order: mechanism, then symptoms, then knobs.
And one rule before any knob: the first law of GC tuning is don't — until you have measured.
Most objects die young — and the JVM is built around that fact
Instrument almost any real program and you find the same shape. The vast majority of
objects become garbage almost immediately — the loop-local String, the temporary
list, the request object. A small minority live for the whole life of the process — the
connection pool, the caches, your Library's book map.
That observation is the generational hypothesis.
The heap is physically organised around it. An object's life runs through three places:
- Eden. Where new objects are born.
- Survivor space. When Eden fills, a minor GC copies the few survivors here and wipes Eden in one cheap sweep. Dead objects cost nothing to collect, and most of them are dead — that is what makes this fast.
- Old generation. Objects that survive a few of those rounds get promoted here. It is collected far less often, by a heavier major or full GC.
Follow the numbers through four minor GCs
The setup: a small heap in the classic young/old layout: Eden 80 MB, two survivor spaces of 10 MB, old generation 160 MB.
Make the invisible visible: each row is one moment, and each cell is used/capacity in MB.
# illustrative output
step Eden S0 S1 Old
1 app runs, Eden fills 80/80 0/10 0/10 10/160
2 minor GC #1 0/80 4/10 0/10 10/160 76 MB dead, 4 MB live copied to S0
3 app runs, Eden fills 80/80 4/10 0/10 10/160
4 minor GC #2 0/80 0/10 5/10 10/160 live from Eden + S0 copied to S1, age +1
...
n minor GC #n 0/80 2/10 0/10 13/160 3 MB reached the age limit: promoted
The trace: the arithmetic of the first collection.
Eden before GC: 80 MB
live (reachable): 4 MB -> copied to S0 ✓ only survivors cost work
dead: 76 MB -> reclaimed by wiping Eden ✓ 76 / 80 = 95% freed for free
Old generation: 10 MB -> untouched by a minor GC ✓ rare, heavier work is deferred
What you see: G1 splits the same idea into equal regions, so the picture is a grid of labelled cells.
# illustrative output: each cell stands for 8 MB of regions
row 1: E E E E E E S O
row 2: O O O O . . . .
E = eden (6 cells, 48 MB) S = survivor (1, 8 MB) O = old (5, 40 MB) . = free (4, 32 MB)
used = 48 + 8 + 40 = 96 MB of 128 MB (real region size is picked by G1 from the heap size, 1 MB to 32 MB)
Why: a minor GC only walks the live objects, so its cost tracks what survives, not what was allocated.
- Interview takeaway: Most objects die young, so Eden is wiped cheaply and only survivors are copied. Objects that survive repeated rounds are promoted to the old generation, which is collected rarely and expensively.
What "unreachable" means
One definition powers both the interview answer and the debugging session.
An object is garbage when it is unreachable: no chain of references leads to it from a GC root. A GC root is one of these:
- a live stack variable,
- a static field,
- a JNI handle.
Garbage is not the same as "unused". Reachable-but-forgotten is precisely what a Java memory leak is, and we'll build one in a minute.
The setup: one object is dropped, one is still held.
Student a = new Student("S-101");
Student b = new Student("S-102");
a = null; // ❌ nothing points at S-101 any more: garbage
// b still points at S-102: reachable, so it stays
Make the invisible visible: follow arrows outward from the roots; whatever you never touch is garbage.
GC ROOTS (stack, statics) HEAP
main's frame: a [ null ] Student "S-101" <- no arrow reaches it ✗ garbage
b -----------------> Student "S-102" <- reachable ✓ kept
- Interview takeaway: Garbage means unreachable from a GC root, not merely unused. A leak is memory that is still reachable but never used again.
The collectors, honestly (JDK 21+)
| Collector | Flag | Choose when | Trade-off |
|---|---|---|---|
| G1 (default) | -XX:+UseG1GC | Almost everything — balanced pause/throughput; region-based, pause-target-driven | Sensible default; tune with a pause goal, not micro-flags |
| ZGC (generational) | -XX:+UseZGC | Latency-critical services, large heaps (multi-GB to TB) — sub-millisecond pauses | Slightly lower throughput, a bit more CPU/memory overhead |
| Parallel | -XX:+UseParallelGC | Batch jobs where total throughput matters and nobody feels a pause | Long stop-the-world pauses are acceptable by design |
| Serial | -XX:+UseSerialGC | Tiny heaps, single-CPU containers, CLI tools | One thread, simplest footprint |
| Shenandoah | -XX:+UseShenandoahGC | Same low-pause goal as ZGC; common in Red Hat builds | Availability varies by JDK distribution |
One short rule per row of the table:
- G1: start here. It splits the heap into regions and collects the ones with the most garbage first, aiming at a pause goal (
-XX:MaxGCPauseMillis, default 200 ms). - ZGC: pick it when a pause of tens of milliseconds already breaks your SLO, or the heap is very large.
- Parallel: pick it for a nightly batch job where only total run time counts.
- Serial: pick it for a tiny container or a command-line tool.
- Shenandoah: the same low-pause goal as ZGC, if your JDK build ships it.
Why did the designers make G1 the default? Most services want decent throughput and bounded pauses without any tuning, so the default targets that balance.
The interview-grade summary: "G1 by default; generational ZGC when pause time is an SLO; Parallel when only throughput matters. And I'd confirm with GC logs before switching anything."
That last sentence is what separates a memorized table from an engineer.
- Interview takeaway: G1 is the balanced default, generational ZGC is for strict pause SLOs, and Parallel is for pure throughput. I confirm with GC logs before switching.
Watch it break: a real memory leak, on purpose
Because the GC collects the unreachable, and a leak is reachable memory
you'll never use again. The classic culprits are long-lived containers that only ever grow:
a static cache with no eviction, listeners nobody unregisters, ThreadLocals in
thread pools. Here is the smallest honest leak — run it and watch it die:
// Run with a small heap so the failure arrives in seconds, not hours:
// java -Xmx64m LeakDemo.java
import java.util.ArrayList;
import java.util.List;
public class LeakDemo {
// The leak: a GC root (static field) holding a list that only ever grows.
// Every element stays REACHABLE, so the collector may not touch it.
static final List<byte[]> CACHE = new ArrayList<>();
public static void main(String[] args) {
int mb = 0;
while (true) {
CACHE.add(new byte[1024 * 1024]); // "cache" 1 MB, never evict
mb++;
if (mb % 16 == 0) System.out.println("cached " + mb + " MB");
}
}
}
// Captured output (JDK 17, -Xmx64m — the exact count varies by JVM and heap overhead):
// cached 16 MB
// Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
// at LeakDemo.main(LeakDemo.java:14)
Watch the leak happen
The setup: the program above, run with a 64 MB heap.
Make the invisible visible: a static field is a GC root, so everything it holds stays reachable.
GC ROOT HEAP (max 64 MB)
static CACHE --------> ArrayList
+--> byte[1 MB] reachable: GC may not touch it
+--> byte[1 MB] reachable
+--> byte[1 MB] reachable
+--> ... one more arrow every loop pass
The trace: the heap fills with data that is all reachable, so each collection frees nothing.
# illustrative output
time cached reachable heap max outcome
t1 16 MB 16 MB 64 MB ✓ room left
t2 32 MB 32 MB 64 MB ✗ GC runs, frees nothing: everything is reachable
t3 48 MB 48 MB 64 MB ✗ GC runs, frees nothing
t4 60 MB 60 MB 64 MB ✗ Full GC cannot free enough: OutOfMemoryError
What you see: the collector works harder and harder, and then the JVM gives up.
# illustrative output (java -Xmx64m -Xlog:gc LeakDemo.java)
[0.210s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 39M->37M(64M) 3.1ms
[0.260s][info][gc] GC(5) Pause Full (G1 Compaction Pause) 61M->60M(64M) 28.4ms
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
Why: the collector frees only the unreachable, and this cache keeps every byte reachable.
Delete the static and let CACHE be a local that goes out of
scope, and the same allocations become collectable garbage. The program churns forever
instead of dying.
That single-word difference is most production leak postmortems in miniature.
The fix: a bounded cache, because "more heap" only delays the crash.
import java.util.LinkedHashMap;
import java.util.Map;
public class LeakFixed {
static final int MAX_ENTRIES = 8;
// ✅ FIX: the eldest entry is evicted once the cache passes its cap
static final Map<Integer, byte[]> CACHE = new LinkedHashMap<>(16, 0.75f, true) {
@Override protected boolean removeEldestEntry(Map.Entry<Integer, byte[]> eldest) {
return size() > MAX_ENTRIES;
}
};
public static void main(String[] args) {
int mb = 0;
while (true) {
CACHE.put(mb++, new byte[1024 * 1024]); // evicted arrays become unreachable
if (mb % 16 == 0) System.out.println("cached " + mb + " MB total, " + CACHE.size() + " kept");
}
}
}
What you see now: the heap stays flat and the program keeps running.
# illustrative output (java -Xmx64m -Xlog:gc LeakFixed.java)
[0.210s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 39M->9M(64M) 3.0ms
[0.260s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 41M->9M(64M) 2.9ms
cached 16 MB total, 8 kept
The same idea applies to the other classic culprits:
- Caches: bound them and give them eviction, or use a library that provides both.
- Listeners: remove them in
finallyor with try-with-resources. - ThreadLocals: call
ThreadLocal.remove()in pooled threads.
- Interview takeaway: A leak is reachable memory you will never use again, so the GC cannot help. The fix is bounded caches, deregistered listeners and removed ThreadLocals, never just more heap.
See the collector work: GC logs
// Healthy churn: allocate garbage that dies young, and watch minor GCs stay cheap.
// java -Xmx256m -Xlog:gc ChurnDemo.java
public class ChurnDemo {
public static void main(String[] args) {
long checksum = 0;
for (int i = 0; i < 2_000_000; i++) {
byte[] scratch = new byte[4096]; // born in Eden…
checksum += scratch.length; // …used once…
} // …unreachable immediately: ideal garbage
System.out.println("done, checksum=" + checksum);
}
}
// Captured log lines (JDK 17, G1; heap shows committed size, not the -Xmx cap):
// [0.528s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->3M(118M) 5.909ms
// [0.553s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 47M->3M(118M) 5.141ms
// [0.587s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 69M->3M(118M) 7.036ms
Read one log line like an engineer
Make the invisible visible: every field of the last line above has a meaning.
[0.587s] JVM uptime when the pause happened
GC(2) the third collection since start (numbering begins at 0)
Pause Young (Normal) (...) a young-generation collection of Eden and survivors
69M->3M(118M) heap used before -> after (current committed size in brackets)
7.036ms how long the application threads were stopped
The trace: the arithmetic on the three lines.
GC(0) 23M -> 3M reclaimed 20M of 23M (87%) ✓
GC(1) 47M -> 3M reclaimed 44M of 47M (94%) ✓
GC(2) 69M -> 3M reclaimed 66M of 69M (96%) ✓ "after" stays at 3M: the live data is flat
What you see: 69M→3M means the young collection reclaimed almost everything, so objects died young and the generational bet paid off. 7ms is the pause your users felt.
A healthy service shows exactly this pattern. Trouble looks different:
- Frequent collections reclaiming little: the "after" number is close to the "before" number.
- Old-generation occupancy climbing after every cycle: the "after" number rises each time.
Pause Fulllines: the heavyweight collection Fig. E1.6 warned about.
# illustrative output
[41.1s][info][gc] GC(88) Pause Young (Normal) (G1 Evacuation Pause) 600M->540M(1024M) 45ms ✗ reclaimed only 60M
[43.0s][info][gc] GC(89) Pause Young (Normal) (G1 Evacuation Pause) 640M->585M(1024M) 52ms ✗ "after" is climbing
[44.7s][info][gc] GC(90) Pause Full (G1 Compaction Pause) 1020M->990M(1024M) 1210ms ✗ 1.2 s stop-the-world
- Interview takeaway: Read a GC line as before-to-after, with the pause time last. Healthy is a low flat "after" and short pauses, while a rising "after" or Pause Full lines point at a leak or a sizing problem.
The tuning playbook (in the only order that works)
| Symptom | Likely cause | First move |
|---|---|---|
| Old gen climbs forever; full GCs reclaim little | A leak — reachable-but-unused (static caches, listeners, ThreadLocals) | Heap dump (jcmd <pid> GC.heap_dump), open in Eclipse MAT/VisualVM, read the dominator tree |
| Frequent minor GCs, high GC CPU | Allocation churn — too much short-lived garbage per request | Profile allocations (JFR: -XX:StartFlightRecording); reuse buffers, cut per-request allocation |
| Occasional long pauses, latency SLO broken | Wrong collector for the goal (or a huge heap on a pause-sensitive service) | Set a G1 pause goal (-XX:MaxGCPauseMillis=100) or move to -XX:+UseZGC; verify with -Xlog:gc |
OutOfMemoryError: Metaspace | Classloader leak (common in hot-redeploy app servers) | Heap dump; look for duplicate classloaders; it's not -Xmx |
| Container OOMKilled but no Java OOM | Total process memory (heap + metaspace + threads + direct buffers) exceeds the container limit | Size with -XX:MaxRAMPercentage=75 and set -Xms=-Xmx in containers; account for off-heap |
Worked example: sizing a heap inside a container
The actors are the container limit and the JVM's own defaults.
- Default max heap: 25% of the memory the JVM sees (
-XX:MaxRAMPercentage=25). - Everything outside the heap: metaspace, code cache, direct buffers and thread stacks.
container limit 2048 MiB
default heap cap (25%) 512 MiB <- often too small for the service
-XX:MaxRAMPercentage=75 (75%) 1536 MiB <- heap cap
left for everything else 2048 - 1536 = 512 MiB
threads: 200 x up to 1 MiB stack up to 200 MiB (-Xss default on 64-bit Linux)
metaspace + code cache + direct buffers the rest of the 512 MiB
If the off-heap total ever exceeds the leftover, the kernel kills the process. The pod shows
OOMKilled (exit code 137) and there is no Java OutOfMemoryError in
the log.
And now the knobs themselves, ranked by how often they turn out to be the right answer.
-Xmx/-Xms— size the heap. Set the two to equal values when running in a container.- The collector choice — see the table above.
-XX:MaxGCPauseMillis— G1's pause target. Read it as a goal, not a guarantee.-Xlog:gc*— not a knob at all. This is the flashlight, and it is how you find out whether any of the others actually helped.
Everything more exotic than that belongs behind a benchmark.
Two tools are worth naming with confidence, because you have now met the workflow they serve:
- jstat and jcmd give you live stats and dumps.
- JFR with Mission Control gives you production-safe profiling.
- Interview takeaway: First read the GC log trend, then size with
-XmxorMaxRAMPercentage, then choose the collector, and only then touch pause goals. I measure before every step.
Three refinements the follow-up questions probe — optional depth
Reference strength. Besides normal (strong) references, Java has three weaker kinds:
SoftReferenceis collected under memory pressure, which suits memory-sensitive caches.WeakReferenceis collected at the next opportunity, which suits canonical maps likeWeakHashMap.- Phantom references are cleanup hooks.
Interview one-liner: "a leak is a strong reference problem; soft/weak references are how caches opt out of causing one."
Not every object hits the heap the same way. Two mechanisms are at work:
- Each thread allocates from its own TLAB (thread-local allocation buffer), which is why
newis nearly free. - The JIT's escape analysis can prove an object never leaves a method and skip real allocation entirely.
Moral: don't hand-optimize allocations the JVM already optimizes — measure first.
finalize() is dead. It is deprecated for removal because it
made GC slower and cleanup unreliable.
The modern answer is try-with-resources (AutoCloseable, §08) for resources,
and Cleaner for the rare native-memory case. Saying this unprompted in an
interview quietly dates your knowledge as current.
Before reading on: your service's GC log shows minor collections every 2 seconds, each reclaiming 95% of the young generation, pauses under 3ms — but the old generation grows by a few MB every hour and never shrinks. Users are happy today. What's your diagnosis, and do you act now or wait?
Reveal the answer
The young-gen pattern is textbook-healthy, so that part needs nothing.
The slow, never-shrinking old-gen climb is the signature of a slow leak: something reachable is accumulating.
You act now, calmly:
- Take a heap dump and another one a few hours later.
- Diff the dominator trees to find the growing collection.
Wait instead, and the ending is a Pause Full storm followed by an OOM, at peak
traffic, because that's when allocation is highest.
# illustrative output
hour old gen used young GC: reclaimed / pause
1 410 MB 95% / 2.8 ms ✓
2 414 MB 95% / 2.9 ms ✗ old gen never shrinks
3 418 MB 95% / 2.8 ms ✗ +4 MB per hour: a slow leak
The whole discipline of this section in one sentence: read the trend, not the snapshot.
Quick reference — Memory and garbage collection
- generational hypothesis
- Almost all objects die almost immediately; a small minority live for the whole process. The heap is physically built around this observation.
- Eden → survivor → old
- New objects are born in Eden. A minor GC copies the few survivors out and wipes Eden cheaply. Objects that survive several rounds are promoted to the old generation, collected rarely by a heavier full GC.
- Why minor GC is cheap
- Dead objects cost nothing to collect — only survivors are copied. And most objects are dead.
- GC root
- Where reachability starts: thread stacks, static fields, and a few JVM internals. Anything not reachable from a root is garbage.
- The knobs, in order
-Xmx/-Xms, then the collector choice, then-XX:MaxGCPauseMillis. And-Xlog:gc*, which is not a knob but the flashlight.- The first law of GC tuning
- Don't — until you have measured.
13 · The road aheadWhere Java Fits in a Backend Career
Java is where enterprise systems land, so it is where AI features have to plug in. The scarce engineer is the one who can write the AI service and read the estate it connects to.
Straight talk: Java is where enterprise systems land.
The payment switch, the core-banking ledger, the order-management system and the claims platform are the systems that every new component must call, feed, or be consumed by.
They are overwhelmingly Spring Boot services maintained by Java teams.
The scarce person in that world is the one who can do both things: write a clean service, and read the estate it plugs into. The one who understands why the integration team is asking about checked exceptions in a client SDK.
For JVM-native shops there are even LangChain-style frameworks on the Java side — LangChain4j and Spring AI. Awareness is enough here; this track does not teach them.
And calling a frontier model from Java is genuinely simple. Here is Claude, through the official SDK:
// Maven project -- add to pom.xml (as of Aug 2026):
// <dependency>
// <groupId>com.anthropic</groupId>
// <artifactId>anthropic-java</artifactId>
// <version>2.34.0</version>
// </dependency>
// Reads ANTHROPIC_API_KEY from your environment -- never hardcode keys.
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.MessageCreateParams;
public class AskClaude {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model("claude-opus-5") // $5 / $25 per 1M tokens, Aug 2026
.maxTokens(16000L)
.addUserMessage("Explain the JVM to a fresher in three sentences.")
.build();
// Read the reply -- and notice this is YOUR curriculum: a builder
// (section 06 design), a List of blocks (07), and a stream pipeline
// with lambdas (07). The SDK assumes you read modern Java. You do.
client.messages().create(params).content().stream()
.flatMap(block -> block.text().stream())
.forEach(t -> System.out.println(t.text()));
}
}
Two framings, one for each audience.
For your own career: Java is the fresher's employability floor in enterprise markets.
The services majors and banks that hire at the largest scale interview on exactly this appendix. Twelve hours here buys entry tickets that pure-Python preparation leaves on the table.
For a stakeholder conversation: "Our AI feature ships when it integrates with the systems we already run — and those systems are Java. An engineer fluent on both sides cuts the integration timeline. The most common failure mode of enterprise AI projects isn't the model. It's the six months lost at the boundary between the AI team and the platform team."
14 · The lablibrary.java — The Classic Project, Done Properly
One complete program, built from scratch, that uses everything in this appendix at once. You get most of it; you write the part that matters.
The console library manager is the classic fresher project, usually done badly: one giant main method, everything public, crashes on bad input.
You're going to do it properly, using every section of this appendix because the job demands it. Here's your starter, complete and runnable as-is (~80% of the plumbing). The checklist below is your 20%:
// STARTER -- run with: java library.java
// (Single-file mode doesn't mind the lowercase filename; the first class
// with a main method is the one that runs.)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Library {
private final List<Book> books = new ArrayList<>();
void add(Book b) { books.add(b); }
int count() { return books.size(); }
List<Book> search(String q) {
return books.stream()
.filter(b -> b.title().toLowerCase().contains(q.toLowerCase()))
.toList();
}
public static void main(String[] args) {
Library lib = new Library();
lib.add(new Book("978-0134685991", "Effective Java"));
lib.add(new Book("978-0132350884", "Clean Code"));
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("\n[1] add [2] search [3] count [0] quit > ");
String choice = in.nextLine().trim();
switch (choice) {
case "1" -> {
System.out.print("isbn: ");
String isbn = in.nextLine().trim();
System.out.print("title: ");
lib.add(new Book(isbn, in.nextLine().trim()));
System.out.println("added.");
}
case "2" -> {
System.out.print("query: ");
lib.search(in.nextLine()).forEach(b -> System.out.println(" " + b));
}
case "3" -> System.out.println(lib.count() + " book(s)");
case "0" -> { System.out.println("bye"); return; }
default -> System.out.println("unknown option: " + choice);
}
}
}
}
// A record: equals/hashCode/toString generated from the fields --
// two Books with the same isbn+title are equal by VALUE, which is
// exactly right for a data carrier (and safe as a HashMap key).
record Book(String isbn, String title) { }
Mission: extend the starter into a real library manager with three additions: issue and return operations with proper failure handling, an ISBN-indexed lookup, and data that survives a restart via a text file.
Every construct below appears because the job needs it — no decoration.
- Compiles and runs single-file with
java library.java— no build tool, no IDE required Bookstays a record;Librarykeeps theArrayListand adds aHashMap<String, Book>ISBN index for O(1) lookup — state in one comment why the record's generatedequals/hashCodemake Book safe as map contentissue(isbn)/returnBook(isbn)track issued books in aHashSetand throw your own unchecked exceptions (e.g.BookAlreadyIssuedException) for invalid operations — caught in the menu loop as a friendly message, never a raw stack trace- At least one interface used meaningfully — e.g. a
Persistenceinterface (save/load) thatLibraryimplements, so a future database version swaps in without touching the menu - Catalog persists to
library.txtusing try-with-resources; restart the program and your added books are still there - At least one stream operation doing real work (the starter's
searchcounts; add a sorted listing or an issued-books report) - Graceful bad input everywhere: unknown menu options, empty titles, issuing a nonexistent ISBN — the loop never crashes
Stretch: a reports menu built on streams — titles sorted
alphabetically, count of issued vs available, search by title or ISBN prefix.
Second stretch: unit-test Library with JUnit 5 (this one needs Maven — add
the org.junit.jupiter:junit-jupiter dependency and let IntelliJ run it;
treat it as your first build-tool outing, setup pointer only).
15 · Interview radarThe Fresher-Round Canon
The questions fresher rounds actually ask, with the answer that clears the round — and, for each, the follow-up that separates the two piles.
These eight are the core of nearly every Java fresher round — services majors, banks, product companies alike. You've now run all of them; what follows is the shape of a strong answer, not a script to recite.
"JDK vs JRE vs JVM?"
Strong answer Give containment first, then currency.
- JVM: the engine that executes bytecode.
- JRE: the JVM plus the libraries — a run-only bundle that hasn't shipped separately since Java 11.
- JDK: the JRE plus the compiler and tools, which is why the JDK is what developers actually install.
Picture it three boxes nested inside each other, and which tool each box adds.
The setup: a one-class program and the two commands that build and run it.
$ javac Hello.java # compile: javac lives in the JDK
$ java Hello # run: needs the JVM and the class libraries
Make the invisible visible: the JDK contains the JRE, which contains the JVM.
JDK
+-- javac, jar, javap, jcmd, jshell ... (developer tools)
+-- JRE (not shipped separately since Java 11)
+-- class libraries (java.base ...)
+-- JVM (executes bytecode)
The trace: the file changes form on its way through the tools.
Hello.java --javac (JDK)--> Hello.class (bytecode) --java (JVM + libraries)--> output
✓ needs the JDK ✓ needs only the runtime part
What you see: on a runtime-only install the run step works and the compile step does not.
# illustrative output
$ javac Hello.java
bash: javac: command not found ✗ no compiler: not a JDK
$ java Hello
Hello, Java ✓ the runtime is there
Land it Naming the Java 11 change — that the standalone JRE is gone — moves you out of the memorized-PDF pile instantly.
"Why is main public static void?"
The real test Whether you can explain each keyword from the JVM's point of view instead of reciting the line.
Strong answer Take the keywords one at a time, from the JVM's point of view.
public: the launcher outside your code must be able to see it.static: it's callable before any object of your class exists. The JVM can't construct one, because with which constructor, and which arguments?void: programs report status via exit codes.String[] args: this is how the command line reaches your program.
Picture it what the launcher does with each keyword, and what arrives in args.
The setup: the classic entry point, plus the instance-method variant that the classic launcher rejects.
public class Hello {
// ✅ classic launcher contract
public static void main(String[] args) {
System.out.println(args.length + " args, first = " + args[0]);
System.exit(2); // void main reports status through the exit code
}
// ❌ TRAP: public void main(String[] args)
// the launcher would need new Hello(): which constructor, which arguments?
// (Recent JDKs are relaxing this rule, but the interview answer is still the classic contract.)
}
The trace: the launcher walks the checklist before your first line runs.
java Hello Asha 42
find class Hello, load it
look up main(String[]) public ✓ visible to the launcher
static ✓ callable with no object: Hello.main(args)
non-static ✗ would need an instance first
build args from the command line, call Hello.main(args)
What you see: the arguments arrive in the array and the exit code carries the status.
$ java Hello Asha 42
2 args, first = Asha
$ echo $?
2
"== vs equals — and the hashCode contract?"
Strong answer == compares references: it asks whether two variables point at the same object. .equals() compares content.
The contract is that objects that are equals MUST have equal hashCodes. The reason is how HashMap works:
hashCodepicks the bucket.equalsconfirms the match within that bucket.
Break that pairing and a stored key becomes unfindable.
Picture it a HashMap whose key class overrides equals but not hashCode, so the second lookup goes to the wrong bucket.
The setup: a Point that defines equality but forgets the hash.
class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
return o instanceof Point p && p.x == x && p.y == y;
}
// ❌ TRAP: hashCode() not overridden, so equal Points get different identity hashes
}
Map<Point, String> m = new HashMap<>();
m.put(new Point(1, 2), "home");
System.out.println(m.get(new Point(1, 2))); // ❌ TRAP: null (almost always)
Make the invisible visible: the two equal Points hash to different buckets.
# illustrative output (hash values and bucket numbers vary)
table of 16 buckets
[ 3] -> Point(1,2) hash=0x1a2b -> "home" <- put() stored it here
[ 9] -> (empty) <- get() looked here: the second Point has hash=0x77c4
The trace: one line per step of the lookup.
put(Point(1,2)) hash -> bucket 3, store entry ✓
get(Point(1,2)) hash -> bucket 9 (different hash, same content) ✗
bucket 9 is empty equals() is never even called ✗ returns null
What you see: the lookup of an equal key misses.
null
Why: HashMap trusts the hash to find the bucket before it ever calls equals.
The fix: derive the hash from the same fields as equals, or use a record, which generates both.
@Override public int hashCode() { return java.util.Objects.hash(x, y); } // ✅ FIX
// or: record Point(int x, int y) { } // ✅ FIX: equals and hashCode generated from the fields
What you see now: the same lookup finds the entry.
home
Land it Add the bonus: records generate both correctly, which is one reason to prefer them for data.
"Why are Strings immutable, and what's the string pool?"
Strong answer Immutability makes Strings three things:
- Safe to share: nobody can change the text under another holder.
- Safe as HashMap keys: a mutating key would change its hashCode and get lost.
- Cacheable: that caching is what enables the pool.
In the pool, identical literals share one object. That is exactly why == "works" on literals and betrays you on runtime strings.
Picture it what a String "change" really does, and why a changing key would be lost.
The setup: two variables, where the second one looks like a modification of the first.
String s = "hello";
String t = s.toUpperCase(); // returns a NEW String; s is untouched
System.out.println(s + " " + t); // Result: hello HELLO
Make the invisible visible: two objects exist afterwards, and the first one never changed.
STACK HEAP
s ---------------> "hello" never changes
t ---------------> "HELLO" a new object
The trace: what would happen if a key could mutate (hypothetical: Strings cannot do this).
put(key "ab") hash("ab") -> bucket 5, stored ✓
key mutates to "xy" (impossible for a String)
get(key) hash("xy") -> bucket 11, not found ✗ entry lost in bucket 5
What you see: the cost of immutability shows up in a concatenation loop: every pass builds a new object.
s += i in a loop:
pass 1 "" + 0 -> new String "0" old "" is garbage
pass 2 "0" + 1 -> new String "01" old "0" is garbage
pass 3 "01" + 2 -> new String "012" n passes = n new Strings, each copy longer than the last
The fix: collect the pieces in one mutable StringBuilder and make a single String at the end.
StringBuilder sb = new StringBuilder(); // ✅ FIX: one growable buffer
for (int i = 0; i < 3; i++) sb.append(i);
String result = sb.toString(); // Result: "012", one final String
What you see now: one builder object in the loop, and a single String at the end.
pass 1 sb "0"
pass 2 sb "01" same builder object, appended in place
pass 3 sb "012" ✓ toString() creates the one final String
Land it Follow through with the
practical consequence: heavy concatenation belongs in a
StringBuilder.
"Array vs ArrayList vs LinkedList?"
Strong answer Three structures, three trade-offs:
- Array is fixed in size, allows primitives, and exposes
.length - ArrayList is growable, holds objects only, gives O(1) access by index, and is the default
- LinkedList is chained nodes — O(1) insert and remove at the ends, but O(n) access by index
Picture it how the same three values are laid out in each structure, which is where the costs come from.
The setup: the same values in all three.
int[] arr = {10, 20, 30};
List<Integer> arrayList = new ArrayList<>(List.of(10, 20, 30));
List<Integer> linked = new LinkedList<>(List.of(10, 20, 30));
// List<int> bad = ...; // ❌ TRAP: compile error, generics need an object type such as Integer
Make the invisible visible: the array and the ArrayList are one block of memory, and the LinkedList is separate nodes.
int[] [ 10 | 20 | 30 ] primitives stored in place
ArrayList Object[] [ ->10 | ->20 | ->30 ] size = 3, capacity = 3 (add() on a full array grows it)
LinkedList first -> [10] <-> [20] <-> [30] <- last each node holds prev and next arrows
The trace: what it costs to reach index 2 and to insert at the front.
arr[2] jump straight to slot 2 ✓ O(1)
arrayList.get(2) jump straight to slot 2 ✓ O(1)
linked.get(2) start at an end, follow arrows node by node ✗ O(n)
arrayList.add(0) shift every element one slot right ✗ O(n)
linked.addFirst relink two arrows ✓ O(1)
Why: contiguous memory gives instant indexing and cache locality, while chained nodes give cheap relinking at the ends only.
Land it Add the honest addendum: in modern practice ArrayList wins almost every real benchmark thanks to cache locality, so "I'd default to ArrayList and reach for LinkedList only for queue/deque patterns" is the senior-sounding answer.
"Abstract class vs interface?"
The real test Whether you lead with the decision rule, not the feature list from the section 06 table.
Strong answer Lead with the decision rule:
- Abstract class: related classes share state and workflow, like your Payment hierarchy.
- Interface: unrelated classes share a capability, like Comparable or Refundable.
Single versus multiple inheritance is what explains why both exist.
Picture it the Payment hierarchy with an interface cutting across it, and which declarations the compiler accepts.
The setup: an abstract class holding shared state and a workflow, and an interface for a capability.
abstract class Payment {
protected final double amount; // shared STATE
Payment(double amount) { this.amount = amount; }
final void process() { validate(); execute(); } // shared WORKFLOW
void validate() { if (amount <= 0) throw new IllegalArgumentException("amount"); }
abstract void execute(); // each subclass supplies its own step
}
interface Refundable { void refund(); } // a CAPABILITY any class can add
class UpiPayment extends Payment implements Refundable {
UpiPayment(double amount) { super(amount); }
void execute() { System.out.println("UPI paying " + amount); }
public void refund() { System.out.println("UPI refunding " + amount); }
}
Make the invisible visible: one class parent, many interfaces, and an unrelated class can share the capability.
Payment (abstract: amount, process()) Refundable (interface: refund())
^ ^ ^ ^
UpiPayment ---------+ +---------------+ |
(extends Payment, implements Refundable) |
CardPayment (extends Payment) GiftVoucher (unrelated class, implements Refundable)
What you see: each declaration either compiles or fails.
- Works:
class UpiPayment extends Payment implements Refundable, Auditable— one parent class, any number of interfaces. - Fails:
class UpiPayment extends Payment, Ledger— compile error, a class can extend only one class. - Fails:
new Payment(10)— compile error,Paymentis abstract and cannot be instantiated.
Why: a class can have only one parent, so the parent should be the shared "is-a" with state, and capabilities go in interfaces.
Land it Citing your own Payment example beats citing Animal and Dog.
"Checked vs unchecked exceptions?"
Strong answer Start with the mechanics.
- Checked: compiler-enforced catch-or-declare.
- Unchecked: the RuntimeException family.
Then give the honest debate from section 08. Checked was meant to force recovery plans for external failures. In practice it:
- breeds swallowed exceptions,
- was dropped by later languages,
- gets wrapped by Spring.
Picture it where each exception sits in the hierarchy, and what the compiler says about each.
The setup: one checked and one unchecked failure.
String text = Files.readString(Path.of("a.txt")); // ❌ compile error: unreported exception IOException;
// must be caught or declared to be thrown
int n = Integer.parseInt("abc"); // compiles; fails at run time: NumberFormatException
Make the invisible visible: everything under Exception is checked, except the branch under RuntimeException.
Throwable
+-- Error unchecked (OutOfMemoryError ...)
+-- Exception CHECKED: compiler forces catch-or-declare
+-- IOException checked
+-- RuntimeException UNCHECKED
+-- NullPointerException
+-- IllegalArgumentException
+-- NumberFormatException
The trace: what the compiler and the runtime each do.
Files.readString(...) throws IOException (checked) ✗ compile error until caught or declared
Integer.parseInt("abc") throws NumberFormatException (unchecked) ✓ compiles, ✗ fails at run time
Why: the compiler checks the first category because the failure is external and recoverable, and leaves the second to your discipline.
The fix: handle it, or wrap it so the cause survives, and never leave an empty catch.
try {
return Files.readString(Path.of("a.txt"));
} catch (IOException e) {
// ❌ TRAP: catch (IOException e) { } // swallowed: the program carries on and nobody knows
throw new java.io.UncheckedIOException("cannot read a.txt", e); // ✅ FIX: cause preserved
}
What you see now: a failure with a message and the original cause, instead of silence.
# illustrative output
Exception in thread "main" java.io.UncheckedIOException: cannot read a.txt
Caused by: java.nio.file.NoSuchFileException: a.txt
Land it Presenting it as a trade-off — with a rule of thumb — is the differentiator.
"Explain the four OOP pillars — with code, not definitions."
The real test This is where memorizers die — the interviewer wants one worked example, not four textbook lines.
Strong answer Walk all four through one worked example:
- Encapsulation — a private
marksfield plus a validating setter, so the invariant lives in one place - Inheritance —
UpiPayment extends Payment, inheritingamountandprocess() - Polymorphism — the
processAllloop callsp.process(), and the runtime type picks theexecute() - Abstraction —
Paymentexposes what (process a payment) and hides how (VPA check vs limit check)
Picture it the one object behind p in the loop, and how its runtime type picks the method.
The setup: a compact version of the Payment example.
abstract class Payment {
protected double amount; // Encapsulation: state kept inside, changed via methods
Payment(double amount) { this.amount = amount; }
void process() { System.out.println("check " + amount); execute(); }
abstract void execute(); // Abstraction: callers see "process", not the how
}
class UpiPayment extends Payment { // Inheritance: gets amount and process() for free
UpiPayment(double a) { super(a); }
void execute() { System.out.println("UPI: verify VPA, pay"); }
}
class CardPayment extends Payment {
CardPayment(double a) { super(a); }
void execute() { System.out.println("CARD: check limit, pay"); }
}
static void processAll(List<Payment> all) {
for (Payment p : all) p.process(); // Polymorphism: same call, different behaviour
}
Make the invisible visible: the variable has one declared type, but the object it points at has its own real type.
STACK (processAll) HEAP
p (type Payment) --------+--> UpiPayment { amount = 500 } <- pass 1: runtime type = UpiPayment
+--> CardPayment { amount = 900 } <- pass 2: runtime type = CardPayment
The trace: the declared type is checked at compile time, and the runtime type picks the method.
pass 1 p.process() -> Payment.process(): "check 500" -> execute() on UpiPayment ✓ UPI version
pass 2 p.process() -> Payment.process(): "check 900" -> execute() on CardPayment ✓ CARD version
What you see: one loop, two behaviours.
check 500
UPI: verify VPA, pay
check 900
CARD: check limit, pay
Land it One worked example covering all four beats four definitions every single time.
Three memory-and-GC questions follow the canon — they're the follow-ups that separate the second interview from the first.
"How does garbage collection actually work?"
Strong answer Tell it in two parts.
- Reachability: an object is garbage when no reference chain from a GC root (live stack variables, static fields) leads to it.
- The generational story from Fig. E1.6:
- objects are born in Eden,
- minor GCs wipe the young generation cheaply because most objects die young,
- survivors age and get promoted,
- the old generation is collected rarely and expensively.
Picture it one object losing its last arrow, and the heap numbers before and after the minor GC that collects it.
The setup: one object is dropped while another stays held.
Student a = new Student("S-101");
Student b = new Student("S-102");
a = null; // ❌ no chain from any root reaches S-101: garbage
Make the invisible visible: the collector starts at the roots and marks everything it can reach.
GC ROOTS (stack, statics) HEAP
b ------------------------------> Student "S-102" ✓ reached: survives
(a is null) Student "S-101" ✗ never reached: garbage
The trace: the minor GC that follows, in order.
1 Eden fills (allocation fails)
2 mark: walk arrows from the roots ✓ S-102 marked live
3 copy live objects to a survivor space (age + 1) ✓
4 wipe Eden in one sweep ✓ S-101 gone, with all other dead objects
What you see: the log line shows heap before, after and the pause.
# illustrative output
[0.553s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 47M->3M(118M) 5.141ms
Land it Naming the generational hypothesis — and that "garbage" means unreachable, not unused — is the whole answer.
"G1 vs ZGC — when would you pick each?"
Strong answer Pick by requirement:
- G1 is the balanced default — region-based, driven by a pause target, and right for almost everything
- Generational ZGC is for when pause time is an SLO — it gives sub-millisecond pauses even on very large heaps, at some throughput cost
- Parallel is for when only batch throughput matters
Picture it the requirement in, the collector out, and a pause budget compared against real log lines.
Make the invisible visible: G1 divides the heap into equal regions and picks the ones with the most garbage first.
# illustrative output: each cell stands for a group of regions
E E E E E S O O
O O O O . . . .
E = eden S = survivor O = old . = free
a young pause copies live objects out of the E and S cells; old cells are collected in small slices
The trace: the decision as a sequence of questions.
Is a pause of tens of ms already breaking the SLO, or is the heap huge? yes -> generational ZGC
Does only total batch time matter, and nobody feels a pause? yes -> Parallel
Otherwise -> G1 (default), pause goal as the knob
What you see: the pause column of the GC log decides whether the SLO is met.
# illustrative output, SLO: no pause above 50 ms
[12.4s][info][gc] GC(40) Pause Young (Normal) (G1 Evacuation Pause) 700M->90M(1024M) 8ms ✓
[19.9s][info][gc] GC(47) Pause Young (Normal) (G1 Evacuation Pause) 980M->95M(1024M) 180ms ✗ breaks the SLO
The fix: set a tighter G1 goal first, or switch the collector, and verify with the log again.
java -XX:MaxGCPauseMillis=50 -Xlog:gc -jar app.jar # G1 with a 50 ms goal (a goal, not a guarantee)
java -XX:+UseZGC -Xlog:gc -jar app.jar # ZGC, then compare the pause column
What you see now: the same log, read the same way, with the pauses back under budget.
# illustrative output
[12.4s][info][gc] GC(40) Pause Young (Normal) (G1 Evacuation Pause) 700M->90M(1024M) 8ms ✓
[19.9s][info][gc] GC(47) Pause Young (Normal) (G1 Evacuation Pause) 980M->95M(1024M) 31ms ✓ under 50 ms
Land it Close with the differentiator: "and I'd read the GC logs before switching — collector changes without measurements are cargo cult."
"Your service OOMs in production every few days — walk me through it."
The real test Whether you have a workflow, not a guess.
Strong answer I'd work through it in four steps.
- Classify it: is it a heap OOM or the container being OOMKilled? Those are different problems,
-Xmxversus total process memory. - Read the GC logs: look at the old-generation trend.
- Take a heap dump with
jcmd, open it in MAT, and read the dominator tree for the growing collection. - Name the usual suspects: static caches without eviction, unremoved listeners, and
ThreadLocals in pools.
Picture it the evidence each step produces, in the order you would look at it.
The setup: the flags to turn on before the next crash, so the evidence exists.
java -Xmx1g -Xlog:gc -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/dumps -jar app.jar
The trace: one line per step.
1 classify heap OOM in the log, or pod OOMKilled with exit code 137? decides the branch
2 GC trend "after" number after each Pause Young / Pause Full ✗ climbing = leak
3 heap dump jcmd <pid> GC.heap_dump /tmp/app.hprof ✓ evidence to open in MAT
4 dominator biggest retained size = the growing collection ✓ found the owner
What you see: the two kinds of failure look different, and the GC trend shows the leak.
# illustrative output
Heap OOM: java.lang.OutOfMemoryError: Java heap space
Container kill: pod status OOMKilled, exit code 137, and no Java exception in the log
GC trend: Pause Full ... 810M->790M(1024M), then 870M->860M(1024M) <- never shrinks
# illustrative output
Class / object Retained heap
Registry (static CACHE) 790 MB
HashMap -> 410,000 entries 789 MB
The fix: bound the cache or deregister, and the same log goes flat.
# illustrative output
Pause Full ... 310M->300M(1024M) then Pause Young ... 420M->300M(1024M) ✓ "after" is flat; no OOM
Land it Bonus points for "the fix is eviction or deregistration, not a bigger heap."
16 · RecapWhat You Can Do Now
What you can now do, and the one exercise that proves it: rebuild the Payment example from an empty file.
- You can write, run, and explain a complete Java program — including every word of
public static void main(String[] args), from the JVM's point of view - You can choose types deliberately: primitives vs wrappers,
StringvsStringBuilder, array vs collection — and say why each pair exists - You can design a small class properly: private fields defending invariants, constructors that refuse garbage, records where data just carries values
- You can build and defend a polymorphic design — and rebuild the Payment hierarchy from a blank file
- You can pick
ArrayList,HashMap, orHashSeton purpose, and read a stream pipeline as comfortably as a loop - You can handle failure like an adult: specific catches, try-with-resources for files, your own exceptions for domain errors, and the checked-vs-unchecked debate stated fairly
- You can demonstrate all six classic gotchas from memory — with the mechanism, not just the symptom
- You can sketch the JVM pipeline (source → bytecode → JIT) and the stack/heap split, and connect both to
==and pass-by-value - You can explain the generational heap, read a GC log line, build (and fix) a real memory leak, choose a collector for an SLO, and debug an OOM with dumps instead of guesses
From this appendix: close the page and rebuild the Payment example from
an empty file — abstract Payment with a shared process(), two
subclasses overriding execute(), and a processAll loop. Then run
it and check against section 06. If you can do that cold, you own the four pillars.
And a cross-reference: revisit the Distributed Systems primer and re-answer its "what happens when the cache dies?" prompt. Java shops interview on both — core Java in the machine round, systems thinking in the next one. The candidates who clear both rounds are the ones who studied them as one subject.