UNIT 1 HOME
0 / 14 CHECKPOINTS
ADVANCED CRASH COURSE UNIT 1 · 44 CHUNKS · ≈ 6 HRS
OOP THROUGH JAVA · UI24PC320CS · UNIT 1 · FAST-TRACK REVISION PATH · SELF-PACED DEEP DIVE

Unit 1, complete. One sitting, forty-four chunks, every PYQ solved.

This is the full Unit-1 syllabus — why OOP exists, classes and objects, Java fundamentals, data and operators, the JVM, your first real class, static and memory, inheritance, polymorphism, final, abstract classes and interfaces — compressed for pace, never for depth. Every concept keeps its micro-examples, every program builds line by line with its real run, and every Unit-1 past-paper question is solved on a ruled sheet at the exact moment it becomes answerable. Add-on topics (keywords, identifiers, instance/static/local variables, static blocks and methods, the arrays deep dive, casts & covariant returns) are woven in where they belong.

PACE≈ 6 hours · 44 chunks of 6–10 minutes · checkpoint after every module
EXAM LOADAll 6 verified Unit-1 PYQs sheet-solved in place + clearly-labelled model questions for the classic favourites
CODEEvery program complete & runnable — stepped line-per-press with its real javac/java output
ZERO-START SAFECollapsible primers cover every prerequisite — start from nothing, finish exam-ready

UNIT SNAPSHOT · WHAT & WHY · 3 MIN

One unit, four ideas, sixty marks of reach.

Unit 1 carries the heaviest exam weight of the five units — its questions run through both released papers (Feb 2024 & Dec 2024). Everything reduces to four ideas: organise (why OOP), describe (classes, data, operators), run (JVM), and relate (inheritance → polymorphism → abstraction). Master these four and Units 2–5 become extensions, not new subjects.

ORGANISE · M1–M2

The disaster procedural code walks into, and the class/object idea that fixes it. Lands PYQ P1·Q1 plus the class-vs-object short answer.

DESCRIBE · M3–M4

Types, variables (all three kinds), casting, arrays, every operator, every branch and loop — the repeat short-answer factory.

RUN · M5–M8

Buzzwords (a 6-marker every paper), JVM rooms, JIT, your first class, static, memory, GC — where "explain" questions live.

RELATE · M9–M12

extends, super, overriding, dispatch, final, abstract, interface — FIVE of the seven sheet PYQs land here. The marks core.

CONCEPT MAP · HOW EVERYTHING CONNECTS · 3 MIN

WHY OOP M1 · PYQ P1·Q1 CLASS + OBJECT M2 · HelloWorld DATA + OPERATORS M3–M4 · shorts factory JVM + BUZZWORDS M5–M6 · 6-marker FIRST CLASS + static M7–M8 · memory map THE MARKS CORE inheritance · dispatch final · abstract · interface M9–M12 · 5 PYQs Follow the arrows left to right — each module strictly needs only what came before it. Jump back any time; the map never lies.
READ IT ONCE NOW · RETURN AFTER EVERY MODULE AND WATCH THE MAP LIGHT UP IN YOUR HEAD

How to use these 44 chunks: each chunk is 6–10 minutes and ends cleanly. Code panels reveal one line per press — press Next line, predict, then confirm against the real terminal run. PYQ sheets are ruled paper: read the question, answer in your notebook first, then compare. At every module boundary a checkpoint asks two honest questions — mark it done and the progress bar remembers you, even after you close the tab.

MODULE 1 / 123 CHUNKS · ≈ 20 MIN

WHY OOP EXISTS — BEFORE A SINGLE LINE OF JAVA

Software fails the same way a shared kitchen fails.

No syntax in this module — deliberately. The exam's very first question (P1·Q1) asks why OOP is needed, and the only full-marks answer is a story you can rebuild under pressure. Six minutes of story now buys you two guaranteed marks later.

CHUNK 1 / 44≈ 7 MIN

Four flatmates, four notebooks, one unanswerable question.

A flat in Kondapur. Four flatmates split expenses, and each keeps their own notebook: Diya logs groceries in hers, Rohit logs rent in his, Sana tracks the Wi-Fi bill on her phone, Arjun scribbles auto fares on sticky notes. Every rupee IS recorded — that's the trap. The data exists; it is just organised around people instead of around the thing itself (the flat's money). That is precisely how procedural programs store state: scattered variables, each function keeping its own copy of the truth.

SYMPTOM 1Scattered facts

"Flat expenses" lives in four places at once. In code: the same real-world thing spread over unrelated variables in unrelated files.

SYMPTOM 2No shared truth

Ask "what did we spend this month?" — four different totals. In code: every function computes its own version of the same answer.

SYMPTOM 3Duplicated operations

"Record an expense" exists four ways — one per notebook. A bug fixed in one copy survives in the other three.

SYMPTOM 4Unanswerable questions

"How much on groceries?" — nobody can say, though every rupee was written down somewhere.

This is not a toy problem — it has a price tag.

A two-branch bank running exactly this pattern (each branch's ledger as its own notebook) once paid out ₹16,000 from a ₹10,000 account, because Branch A's copy said ₹2,000 remained while Branch B's still said ₹10,000. Scattered truth is how real money disappears.

CHUNK 2 / 44≈ 7 MIN

The fix: one register, four needs, four names.

The flat's fix is obvious once said aloud: one shared register on the kitchen shelf, with fixed columns and fixed rules for writing in it. OOP is that fix, formalised. Watch each failure earn its named cure — one pair per press:

FAILURE → CURE 1Scattered facts → a CLASS

One named unit — ExpenseRegister — keeps the data AND the operations on it together. The thing itself finally exists in the program.

FAILURE → CURE 2No shared truth → ENCAPSULATION

The register's pages aren't loose — state changes only through the register's own operations. Nobody scribbles sideways.

FAILURE → CURE 3Duplication → ONE METHOD each

"Add expense" is written once, used by all four flatmates, and bug-fixed in exactly one place.

FAILURE → CURE 4Unanswerable → ONE SOURCE OF TRUTH

Every question has exactly one answer because everyone reads the same record. "How much on groceries?" takes one lookup.

✓ FOUR NEEDS, FOUR NAMES — CLASS · ENCAPSULATION · METHODS · SINGLE TRUTH. THAT LIST IS THE EXAM ANSWER.

Re-costume it and it still works: three cricket scorebooks for one match (three different run rates), three pharmacy stock registers for one shelf (phantom stock), two bank-branch ledgers for one account (the ₹16,000 leak). Any of these stories rebuilds the same four pairs — remember ONE story, own them all.

CHUNK 3 / 44 · PYQ≈ 6 MIN · NOTEBOOK FIRST

This exact question has been asked. Answer it in your notebook first.

The one Unit-1 PYQ that lands before any syntax exists — so its model answer is the story you just built, in two-column form. (Every later PYQ in this file gets a full runnable model program; this one is prose by design — you haven't met Java yet, and neither had the paper-setter's intent.)

PAST PAPER · PAPER 1 · QUESTION 1 2 MARKSUNIT IREVISIT: CHUNKS 1–2
P1 · Q1 · 2m

Q1. State the need of OOP over procedural programming. [2 M]

MODEL ANSWER — ANY TWO PAIRS, FAILURE → WHAT OOP ADDED · ONE PER PRESS ↓

1

Need 1 — one class per real thing: procedural code scatters one thing's data across variables and files; OOP keeps related data and its operations together in one named unit (a class).✓ 1

2

Need 2 — encapsulation: procedural state can be modified from anywhere; OOP state changes only through the unit's own operations, so it cannot be silently corrupted.✓ 1

3

Need 3 — one method per operation: procedural programs duplicate the same step in many places (a bug fixed in one copy survives in the rest); OOP defines each operation once, reused by all.

4

Need 4 — one source of truth: with the data in one object, every question has exactly one answer — no more four totals for one flat.

Exam craft: the question asks for the need — so each point must name what OOP added, shown against what failed. Only listing procedural's problems scores half. Any two pairs = 2/2.

Two pairs, failure → fix, in any costume you remember. ✓ 2/2

CHECKPOINT · MODULE 1

Close your eyes and rebuild: the four symptoms, their four named cures, and the two-pair shape of P1·Q1. If any pair is fuzzy, re-run Chunk 2 — it's 90 seconds.

MODULE 2 / 125 CHUNKS · ≈ 38 MIN

CLASS, OBJECT & YOUR FIRST RUNNING PROGRAM

The register gets a name. Then it gets a body.

Module 1 ended with "put the data and its operations in one named unit". This module makes that unit real: what a class actually is, what an object actually is, and the smallest Java program that compiles and runs — typed line by line with its real terminal output. Two evergreen short answers ("class vs object", "explain main()") land here, plus the first add-on topic.

CHUNK 4 / 44≈ 7 MIN

class = the ticket template. object = the ticket in your hand.

A cinema designs one ticket template: every ticket will have a movie name, a seat, a price, and a barcode that can be scanned. On Friday night the counter prints hundreds of tickets from that one template — each with its own movie, seat and price. The template is the class; each printed ticket is an object. The template costs nothing until printing starts — a class occupies no memory for its instance data; objects do.

THE CLASSOne template, written once

Declares what every ticket will have (fields) and what every ticket can do (methods).

class Ticket { String movie; int seat; void scan() { ... } }
THE OBJECTOne printed ticket, real values

new is the printing press — every press produces a fresh object with its own copies of the fields.

Ticket t1 = new Ticket(); t1.movie = "Kalki"; t1.seat = 14;
MANY FROM ONEHundreds of tickets, one template

t1, t2, t3… all from class Ticket, each independent: changing t1.seat touches nobody else's seat.

SAY IT PRECISELYAn object is an instance of a class

That single sentence — with the word instance — is the phrase examiners scan for.

CLASSOBJECT
Blueprint / template — a logical descriptionReal, usable thing built from it — a physical reality in memory
Written once by the programmerCreated any number of times at runtime with new
Allocates no memory for instance dataEach object gets its own copy of every instance field on the heap
Declared: class Ticket { ... }Created: Ticket t = new Ticket();
Classic 2-mark short answer: two rows of this table + one example pair = full marks. (A model short answer — not one of the 6 verified Unit-1 PYQs, but the class-vs-object contrast is exam bedrock.)
CHUNK 5 / 44≈ 9 MIN

HelloWorld.java — every line typed, compiled, run. For real.

This is the smallest complete Java program. Press Next line, predict what the line does, then read its explanation below. When the file is complete, the black terminal shows the actual compile-and-run — the same two commands you'll type in Lab 1.

ZERO-START PRIMER · "I've never used a terminal or compiler" — 90 seconds

A terminal is a text window where you type commands instead of clicking. A compiler (javac) is a translator: it reads your .java text file and produces a .class file of bytecode — instructions for the Java Virtual Machine, not for your CPU directly (that distinction becomes Module 5's star). Then java HelloWorld starts the JVM, which executes that bytecode. Two commands, always in this order: javac translates, java runs. One hard rule before you start: the file must be named HelloWorld.java — exactly matching the public class name, capitals included.

HelloWorld.java — COMPLETE & RUNNABLE
1// My first Java program — file name MUST be HelloWorld.java
2public class HelloWorld
3{
4 public static void main(String[] args)
5 {
6 System.out.println("Hello, World!");
7 System.out.println("Unit 1, I am coming for you.");
8 }
9}
TERMINAL — THE REAL RUN
$ javac HelloWorld.java
$ ls
HelloWorld.java  HelloWorld.class
$ java HelloWorld
Hello, World!
Unit 1, I am coming for you.
javac produced HelloWorld.class (bytecode); java handed it to the JVM. No errors, two lines printed — in source order, top to bottom.
Line-by-line, what you just typed: line 2 declares the class (the template — here it holds only behaviour); line 4 is main, the fixed door the JVM knocks on; lines 6–7 call println, which prints its text and moves to a new line. Notice the house style: every { and every } stands on its own line, vertically aligned with its partner — you can SEE each block's start and end at a glance, and so can the examiner.
The three beginner errors that eat lab time (and viva marks):

① File saved as helloworld.javaclass HelloWorld is public, should be declared in a file named HelloWorld.java. ② A missing semicolon → compile error on the next line, which confuses everyone once. ③ Running java HelloWorld.class instead of java HelloWorldClassNotFoundException. The run command takes the class name, not the file name.

CHUNK 6 / 44≈ 7 MIN

The five pieces of main() — why every word is non-negotiable.

"Explain the signature of main()" is a recurring 2–4 mark short answer, and it's also the line you'll type most often in your life. Five words, five reasons — one per press:

PIECE 1public — visible from outside

The JVM lives outside your class and must be allowed to call in. Make main private and the JVM is locked out: Error: main method not found.

PIECE 2static — callable with no object

Chicken-and-egg: objects are created by running code, but no code has run yet. static lets the JVM call main on the class itself, before any object exists. (Full static story: Module 8.)

PIECE 3void — returns nothing

When main ends, the program ends — there is nobody left to hand a return value to.

PIECE 4main — the agreed name

A contract, not a keyword. The JVM looks for exactly this spelling; Main or mian compiles fine and then fails at run time.

PIECE 5String[] args — the inbox

Anything typed after the class name — java Billing march 2026 — arrives here as strings: args[0] is "march", args[1] is "2026".

✓ PUBLIC (REACHABLE) · STATIC (NO OBJECT NEEDED) · VOID (NOTHING TO RETURN) · MAIN (AGREED NAME) · STRING[] ARGS (THE INBOX). FIVE PIECES = FULL MARKS.

Exam craft: the trap phrasing is "why is main static?" — one precise sentence wins it: "because the JVM must invoke it before any object of the class exists, and static members are callable on the class itself." Memorise that sentence as-is.

CHUNK 7 / 44 · ADD-ON≈ 8 MIN

Keywords vs identifiers — which words are Java's, which are yours.

You just typed eight different words in seven lines. They split into exactly two families: keywords — words Java has reserved for itself, always lowercase, with fixed meanings — and identifiers — names you invent for classes, variables and methods. Confusing the two is a compile error; naming them correctly is a guaranteed short-answer.

FAMILYIN HelloWorld.javaTHE RULE
Keywordspublic class static void~50 reserved words. Fixed meaning, always lowercase, can NEVER be used as a name. (const and goto are reserved but unused — a classic trick question.)
Identifiers (yours)HelloWorld argsNames you chose. You could rename both and the program still runs identically.
Identifiers (library's)String System out printlnAlso identifiers — just chosen by Java's library authors. String is NOT a keyword — it's a class name, which is why it's capitalised.
Literals, not keywordstrue false nullOfficially literals (values), not keywords — but equally unusable as names. Papers love this distinction.

The four identifier rules, then seven candidates judged one per press — predict legal/illegal before pressing:

RULE 1First character

A letter, _ or $never a digit.

RULE 2After that

Letters, digits, _, $. No spaces, no hyphens, no other symbols.

RULE 3No reserved words

Any keyword (or true/false/null) is off the table.

RULE 4Case-sensitive

total, Total and TOTAL are three different identifiers. Convention (not law): ClassName, variableName, CONSTANT_NAME.

LEGALupiAmount

Letters only, starts with a letter. Textbook camelCase.

LEGAL_backupCopy & $rate

Underscore and dollar are valid first characters — legal, though conventions reserve them for special uses.

ILLEGAL2ndSeat

Starts with a digit — breaks Rule 1. Write seat2 or secondSeat.

ILLEGALticket-price

Hyphen is the minus operator — Java reads "ticket minus price". Use ticketPrice.

ILLEGALclass

Keyword — Rule 3. But Class1 or myClass? Perfectly legal.

LEGAL (SADLY)x, a1, temp

Legal — and terrible. The compiler accepts them; the human re-reading your exam answer (the examiner!) will not.

✓ SCORE: 4 LEGAL, 3 ILLEGAL. IF YOU CALLED ALL SEVEN CORRECTLY, THIS TOPIC IS CLOSED FOREVER.

CHUNK 8 / 44≈ 7 MIN

IS-A vs HAS-A — the two ways classes relate. Plus your first self-check.

Before Module 9 spends four chunks on inheritance, plant the seed now — it costs two minutes and makes extends feel obvious later. Classes connect in exactly two ways, and the test is a plain-English sentence:

IS-A · INHERITANCE"A Car IS A Vehicle" ✓ sounds right

So Car may extend Vehicle and inherit everything a vehicle has. Wrong-way check: "a Vehicle is a Car" sounds wrong — inheritance has a direction.

class Car extends Vehicle { ... }
HAS-A · COMPOSITION"A Car HAS AN Engine" ✓ sounds right

"A Car is an Engine" is nonsense — so no extends. The engine becomes a field inside the car.

class Car { Engine engine; // HAS-A = a field }
THE CLASSIC TRAPLibrary HAS Books. A Library is not a Book.

Beginners reach for inheritance whenever two classes feel "related". Say the sentence out loud first — it never lies.

SELF-CHECK · MODULE 2 · ANSWER ALL FIVE IN YOUR HEAD BEFORE UNLOCKING

  1. One sentence: what is an object, using the word instance?
  2. Your file is hello.java but the public class is Hello. Compile, run, or fail — and with what message?
  3. Why exactly must main be static?
  4. Legal or illegal: $total · new · o2Level · 2gether?
  5. Hospital and Doctor: IS-A or HAS-A? And Doctor and Person?
Check yourself honestly:
  1. An object is an instance of a class — a runtime copy with its own field values, created by new.
  2. Compile fails: class Hello is public, should be declared in a file named Hello.java. Public class name and file name must match exactly.
  3. The JVM must call it before any object exists; static members are callable on the class itself, no object needed.
  4. $total legal · new illegal (keyword) · o2Level legal (digit not first) · 2gether illegal (digit first).
  5. Hospital HAS-A Doctor (a hospital is not a doctor). Doctor IS-A Person — inheritance direction: Doctor extends Person.
CHECKPOINT · MODULE 2

You can now: define class vs object with the word instance, type + compile + run HelloWorld from memory, defend all five pieces of main(), judge any identifier, and sort IS-A from HAS-A. If the self-check cost you more than one answer, re-run that chunk before moving on.

MODULE 3 / 125 CHUNKS + DEEP DIVE · ≈ 52 MIN

DATA — TYPES, VARIABLES (ALL THREE KINDS), CASTING, INPUT, ARRAYS

Every value in Java lives in a labelled, size-fixed box.

Java is strongly typed: every variable declares its type up front and keeps it forever. This module is the short-answer factory — primitive sizes and ranges, the three kinds of variables (an add-on topic papers quietly assume you know), casting, reading input, and arrays with their famous crash.

CHUNK 9 / 44≈ 9 MIN

Eight primitives — and the one formula that replaces memorising ranges.

Java has exactly eight primitive types. Don't memorise eight ranges — memorise one formula: a signed type of n bits holds −2n−1 to 2n−1−1. One bit is spent on the sign; the −1 on top exists because zero occupies one of the non-negative slots.

TYPESIZERANGE / VALUESYOU'D USE IT FOR
byte8 bits−128 to 127Raw file/network bytes
short16 bits−32,768 to 32,767Rare; legacy formats
int32 bits≈ −2.14 × 10⁹ to 2.14 × 10⁹The default whole number — counts, seats, marks
long64 bits≈ ±9.2 × 10¹⁸Phone numbers, timestamps, populations — write 98490L
float32 bits~7 significant digitsRare; must write 4.5f
double64 bits~15 significant digitsThe default decimal — prices, averages, percentages
char16 bitsOne Unicode character'A', '₹', 'అ' — single quotes
booleanJVM-dependenttrue / false onlyFlags — never 0/1 like C
FORMULA CHECKbyte: n = 8

−2⁷ to 2⁷−1 = −128 to 127. Matches the table — the formula regenerates every signed row.

THE OVERFLOW TRAP127 + 1 = −128 (in byte)

Exceed the top and the value wraps around to the bottom — no error, no warning, just a silently wrong number. This is a favourite "predict the output" trick.

NOT A PRIMITIVEString is a class

Capital S, double quotes, has methods like .length(). Papers ask "list the primitive types" hoping you'll include String — don't.

WHY FIXED SIZES MATTERSame size on every machine

C's int changes size per machine; Java's is 32 bits everywhere. That guarantee is one of the buzzwords (portable) meeting you in Module 5.

CHUNK 10 / 44 · ADD-ON≈ 9 MIN

One class, three kinds of variables — where each lives and dies.

Every variable you will ever declare in Java is one of exactly three kinds, decided purely by where you declare it. Watch one small class use all three — the panel below is complete and runnable. As you press, ask of each variable: how many copies exist, and when does it die?

CanteenCounter.java — COMPLETE & RUNNABLE
1public class CanteenCounter
2{
3 static int totalOrders = 0; // STATIC — one copy for the whole class
4 String studentName; // INSTANCE — one copy per object
5 void order(int items)
6 {
7 int bill = items * 40; // LOCAL — born and dies inside this call
8 totalOrders++;
9 System.out.println(studentName + " pays ₹" + bill + " | orders so far: " + totalOrders);
10 }
11 public static void main(String[] args)
12 {
13 CanteenCounter a = new CanteenCounter(); a.studentName = "Meera";
14 CanteenCounter b = new CanteenCounter(); b.studentName = "Vikram";
15 a.order(2);
16 b.order(3);
17 }
18}
TERMINAL — THE REAL RUN
$ javac CanteenCounter.java
$ java CanteenCounter
Meera pays ₹80 | orders so far: 1
Vikram pays ₹120 | orders so far: 2
studentName differs per object (Meera / Vikram) — instance. totalOrders keeps counting ACROSS objects (1, then 2) — static, one shared copy. bill was recomputed fresh in each call — local, already gone.
Read the output like an examiner: two objects, two different names → instance variables are per-object. One counter that reached 2 → static is class-wide. bill never survived past line 10 (the method's closing }) → local dies with its method call. This single program is your model answer for "differentiate instance, static and local variables".

KINDDECLAREDCOPIESBORN → DIESDEFAULT VALUE
LocalInside a methodOne per callMethod starts → method returnsNONE — using it uninitialised is a compile error
InstanceIn class, no staticOne per objectnew → object garbage-collected0 / 0.0 / false / null, automatic
StaticIn class, with staticExactly one, everClass loads → program ends0 / 0.0 / false / null, automatic
The asymmetry papers test:

Instance and static variables get automatic defaults; locals get nothing. int x; System.out.println(x); inside a method is the compile error variable x might not have been initialized — but the same two lines as a field print 0 happily. Predict-the-output questions are built on exactly this.

CHUNK 11 / 44≈ 8 MIN

Casting — pouring between boxes. One direction is free, one needs a signature.

Pour a small bottle into a big jug: nothing can spill — Java does it silently (widening). Pour a jug into a bottle: it may overflow — Java refuses unless you sign a waiver, the cast (int) (narrowing). One rule, both directions:

WIDENING · AUTOMATICsmall → big, no data can be lost

byte → short → int → long → float → double. No syntax needed.

int marks = 87; double d = marks; // 87.0 ✓ silent
NARROWING · EXPLICITbig → small, you sign the waiver

Without the cast: compile error incompatible types: possible lossy conversion.

double avg = 86.75; int shown = (int) avg; // 86 — decimals CUT, not rounded
THE DIVISION TRAP7 / 2 is 3, not 3.5

int ÷ int stays int — the fraction is discarded before any assignment. Fix: make one side double: 7 / 2.0 → 3.5, or (double) 7 / 2.

THE PROMOTION RULEbyte + byte = int

Arithmetic promotes small types to int automatically, so byte c = a + b; fails to compile even when a and b are bytes. Write (byte)(a + b). Classic 2-marker.

One line to remember it all: widening is a gift, narrowing is a waiver. And the waiver truncates(int) 9.99 is 9, never 10. If an exam program prints a suspiciously whole number, hunt for an int division or a narrowing cast.

CHUNK 12 / 44≈ 7 MIN

Scanner — three lines and your program listens.

Every lab program starts by reading input. The ritual is exactly three moves: import the class, build a Scanner on System.in, then call the next…() method matching the type you want. Full runnable program:

MessBill.java — COMPLETE & RUNNABLE
1import java.util.Scanner; // move 1: tell Java where Scanner lives
2public class MessBill
3{
4 public static void main(String[] args)
5 {
6 Scanner sc = new Scanner(System.in); // move 2: aim it at the keyboard
7 System.out.print("Days ate in mess: ");
8 int days = sc.nextInt(); // move 3: read, typed
9 System.out.print("Rate per day: ");
10 double rate = sc.nextDouble();
11 System.out.println("Mess bill: ₹" + (days * rate));
12 sc.close();
13 }
14}
TERMINAL — THE REAL RUN
$ javac MessBill.java && java MessBill
Days ate in mess: 26
Rate per day: 82.5
Mess bill: ₹2145.0
Bold = what the user typed. print (no ln) kept the cursor on the same line so the question and answer share a row.
The method must match the type: nextInt() → int, nextDouble() → double, next() → one word, nextLine() → the whole line. Typing "abc" into nextInt() throws InputMismatchException at run time — a compile-vs-runtime error example papers love.
CHUNK 13 / 44≈ 9 MIN

Arrays — one tray, numbered slots, and the crash every Java programmer meets.

Sixty students' marks should not be sixty variables. An array is one tray of numbered slots — all the same type, size fixed at creation, numbering starts at 0. That last fact produces Java's most famous runtime crash, which you'll now cause on purpose:

CREATESize fixed at birth
int[] marks = new int[5]; // slots 0,1,2,3,4 — all start at 0

Or with values: int[] m = {70, 82, 91, 65, 88};

ACCESSIndex 0 is the FIRST slot
marks[0] = 70; // first marks[4] = 88; // LAST of 5

Last valid index is always length − 1.

MEASURE.length — no parentheses
marks.length // array: field → 5 "Kalki".length() // String: method

Array .length vs String .length() — a beloved 1-mark trick.

MarksReport.java — RUNNABLE, CRASH INCLUDED ON PURPOSE
1public class MarksReport
2{
3 public static void main(String[] args)
4 {
5 int[] marks = {70, 82, 91, 65, 88}; // array literal — braces on one line are values, not a block
6 int total = 0;
7 for (int i = 0; i < marks.length; i++) // i < length, NEVER <=
8 {
9 total += marks[i];
10 }
11 System.out.println("Average: " + (total / (double) marks.length)); // cast! chunk 11
12 System.out.println("Slot 5: " + marks[5]); // THE CRASH — there is no slot 5
13 }
14}
TERMINAL — THE REAL RUN
$ javac MarksReport.java && java MarksReport
Average: 79.2
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 5
  at MarksReport.main(MarksReport.java:12)
It COMPILED cleanly and even ran line 11 first — then died at line 12. Bounds are checked at RUN time, not compile time. C would have silently read garbage memory here; Java refuses. That refusal is the buzzword "robust" — arriving in Module 5.
Read the crash like a pro: the exception names the index (5), the length (5), the file and the exact line (12). Java crash messages are literally the answer key — students who read them finish labs twice as fast.
CHUNK 13+ · ADD-ON DEEP DIVE≈ 10 MIN

Arrays, the full toolbox — every declaration style, 2D, jagged, for-each.

Chunk 13 gave you the tray and the crash. This deep dive gives you everything else papers and labs draw from: the four legal ways to declare an array, the loop that cannot go out of bounds, tables (2D), ragged tables (jagged), and the .length family. All of it lands in one runnable file at the end.

STYLE 1Sized, empty — values later
int[] a = new int[3]; // slots 0,1,2 — all default to 0

Size fixed at birth; every slot auto-defaults (0 / 0.0 / false / null — same table as instance fields, chunk 10).

STYLE 2Literal — values at birth
int[] b = {10, 20, 30}; // size inferred: 3

Braces on ONE line here are values, not a block — the single place inline braces are house-legal. Only allowed at declaration.

STYLE 3new + literal — reusable anywhere
int[] c = new int[]{5, 15, 25};

Same result as style 2, but THIS form also works later: c = new int[]{9, 9}; — a bare {9, 9} after declaration refuses to compile.

STYLE 4C-style brackets — legal, frowned upon
int d[] = {1, 2}; // brackets on the NAME — C legacy

Compiles identically; every style guide says put brackets on the TYPE (int[] d) — "the type is int-array". Papers ask "which declarations are valid?" — all four are.

Now the two ideas that upgrade you from 1D to tables — 2D is literally an array OF arrays, and once you see that, jagged is free. One press each:

IDEA 1 · 2D = ARRAY OF ARRAYSint[][] marks = { {70, 82}, {91, 65} };

The outer array holds two references, each aiming at its own inner row on the heap. marks[1][0] reads: follow reference 1, then take slot 0 → 91. Row first, column second — always.

IDEA 2 · TWO LENGTHSmarks.length vs marks[0].length

marks.length = number of ROWS (2). marks[0].length = slots in row 0 (2). Mixing them up in a nested loop is THE classic 2D bug — and a favourite predict-the-output trap.

IDEA 3 · JAGGEDRows of different lengths

int[][] jagged = new int[3][]; builds only the outer array — each row is born separately, any size: jagged[1] = new int[3];. Real use: attendance per section, marks per elective — rows that genuinely differ.

IDEA 4 · FOR-EACHThe loop that cannot crash

for (int x : b) — no index, no <= mistake, no bounds exception possible. Trade-off: you get each VALUE but no index, and writing to x does not change the array (it's a copy — pass-by-value again, chunk 30's preview).

✓ 2D = ARRAY OF ROW-REFERENCES · TWO LENGTHS, ROWS vs SLOTS · JAGGED = ROWS BORN SEPARATELY · FOR-EACH = BOUNDS-PROOF READING.

ArraysTour.java — COMPLETE & RUNNABLE
1public class ArraysTour
2{
3 public static void main(String[] args)
4 {
5 int[] a = new int[3]; // style 1: sized — 0,0,0
6 int[] b = {10, 20, 30}; // style 2: literal — values, not a block
7 int[] c = new int[]{5, 15, 25}; // style 3: new + literal
8 int d[] = {1, 2}; // style 4: C-style — legal, discouraged
9 a[0] = 7;
10 int sum = 0;
11 for (int x : b) // for-each: no index, no bounds risk
12 {
13 sum += x;
14 }
15 System.out.println("sum of b = " + sum + " | c[2] = " + c[2] + " | d[1] = " + d[1]);
16 int[][] marks = { {70, 82}, {91, 65} }; // 2D: an array OF arrays
17 System.out.println("marks[1][0] = " + marks[1][0]); // row 1, slot 0
18 int[][] jagged = new int[3][]; // jagged: outer only — rows born separately
19 jagged[0] = new int[1];
20 jagged[1] = new int[3];
21 jagged[2] = new int[2];
22 for (int r = 0; r < jagged.length; r++) // rows via .length…
23 {
24 System.out.println("row " + r + " holds " + jagged[r].length + " slots"); // …slots via [r].length
25 }
26 System.out.println("a[0] = " + a[0] + " | a[1] defaulted to " + a[1]);
27 }
28}
TERMINAL — THE REAL RUN
$ javac ArraysTour.java && java ArraysTour
sum of b = 60 | c[2] = 25 | d[1] = 2
marks[1][0] = 91
row 0 holds 1 slots
row 1 holds 3 slots
row 2 holds 2 slots
a[0] = 7 | a[1] defaulted to 0
All four declaration styles ran identically. The jagged loop printed three DIFFERENT row lengths — proof that each row is its own independent array. And a[1], never assigned, defaulted to 0 (arrays get defaults; locals don't — chunk 10's asymmetry).
The nested-loop template to memorise (works for square AND jagged, because the inner bound asks THE ROW): outer r < t.length, inner c < t[r].length. Hard-code the inner bound to a number and jagged data crashes you — exactly chunk 13's exception, one dimension deeper.
Three array traps that fill papers:

int[] x = new int[3]{1,2,3}; — size AND literal together refuses to compile: give one or the other. ② A bare literal after declaration (x = {9, 9};) also refuses — use style 3's new int[]{9, 9}. ③ marks.length() with parentheses — arrays' length is a FIELD; only String's is a method (chunk 13's beloved 1-marker).

CHECKPOINT · MODULE 3

Rebuild from memory: the range formula (−2ⁿ⁻¹ to 2ⁿ⁻¹−1), the three variable kinds with their lifetimes, widening-vs-narrowing in one line, the Scanner ritual, why marks[5] crashed a length-5 array, and the two lengths of a 2D array (t.length rows · t[r].length slots). Fuzzy on one? That chunk is a 90-second re-run.

MODULE 4 / 125 CHUNKS · ≈ 42 MIN

OPERATORS & CONTROL FLOW — THE DECISION MACHINERY

Values you can now store. Time to compute and decide with them.

Every operator family, precedence, the bitwise set (a guaranteed short-answer), branching, loops — and a drill program that uses all of it in one realistic build. After this module you can hand-trace any Unit-1 "predict the output" question.

CHUNK 14 / 44≈ 9 MIN

Arithmetic → relational → logical, and the precedence ladder.

Three families do 95% of all work, and they chain: arithmetic makes numbers, relational turns numbers into booleans, logical combines booleans. Precedence decides who goes first when they mix.

FAMILYOPERATORSTHE TRAPS
Arithmetic+ − * / %7/2 is 3 (int÷int, chunk 11) · % is remainder: 10 % 3 = 1, 17 % 5 = 2 — used for even/odd, last digit, cycling
Increment++ --x++ uses then bumps; ++x bumps then uses. int y = x++; vs int y = ++x; differ by exactly 1 — the classic 1-marker
Relational== != < > <= >== assigns, == compares. And for Strings use .equals(), never == (== compares references — Unit-2 preview, but the trap appears in Unit-1 papers)
Logical&& || !Short-circuit: in a && b, if a is false, b is never evaluated. (x != 0 && 10/x > 2) is safe for x = 0 for exactly this reason — a favourite "why doesn't this crash?" question
Ternarycond ? yes : noA one-line if-else that produces a value: String result = marks >= 40 ? "PASS" : "FAIL";
PRECEDENCE LADDERTop binds first

1. ++ -- ! (unary)
2. * / %
3. + −
4. < <= > >=
5. == !=
6. && then ||
7. = += (last, rightmost)

TRACE IT2 + 3 * 4 > 10 && true

3*4=12 → ② 2+12=14 → ③ 14>10=true → ④ true&&true=true. Four steps, strictly by the ladder.

THE HONEST RULEWhen in doubt, bracket

Parentheses beat everything and cost nothing. In exam answers, brackets also show the examiner your order — free partial marks even if arithmetic slips.

CHUNK 15 / 44≈ 9 MIN

Bitwise & shifts — operating on the 32 switches inside an int.

An int is 32 on/off switches. Bitwise operators flip them directly — and "explain bitwise operators with examples" is a classic 4–6 mark favourite. Work every example on 8 bits with the number pair 12 (00001100) and 10 (00001010):

OPNAMERULE (per bit)12 op 10 →
&AND1 only if BOTH are 100001000 = 8
|OR1 if EITHER is 100001110 = 14
^XOR1 only if they DIFFER00000110 = 6
~NOT (unary)flip every bit~12 = −13 (always −n−1)
<<Left shiftshift left, fill 0s = × 2 per step12 << 2 = 48
>>Signed rightshift right, copy the sign bit = ÷ 2 per step12 >> 2 = 3 · −12 >> 2 = −3
>>>Unsigned rightshift right, always fill 0ssame on positives; −1 >>> 28 = 15
THE >> VS >>> QUESTIONThey differ ONLY on negatives

>> preserves the sign (arithmetic shift); >>> stuffs zeros in from the left, so a negative becomes a huge positive. One sentence + one example each = full marks on the differentiate question.

DON'T CONFUSE& vs &&

& works on bits (and never short-circuits); && works on booleans and short-circuits. Same shape, different families.

WHY ANYONE CARESFlags, masks, speed

File permissions (rwx = 3 bits), network headers, graphics — anywhere 32 booleans must fit in one int. x << 3 is also a famously fast ×8.

XOR PARTY TRICKa ^ b ^ b == a

XOR with the same value twice returns the original — the basis of simple encryption and the "find the odd one out" interview classic.

CHUNK 16 / 44≈ 8 MIN

Branching — if ladders for ranges, switch for exact matches.

Two tools, one decision rule: testing a value against ranges (marks bands, ages, prices) → if / else-if ladder. Testing against exact values (menu choice, day number, grade letter) → switch. Both, runnable:

RANGES → IF LADDEROrder matters: strictest first
if (marks >= 90) g = 'O'; else if (marks >= 75) g = 'A'; else if (marks >= 40) g = 'B'; else g = 'F';

Only the FIRST true branch runs; the rest are skipped. Put >= 40 first and everyone above 40 gets 'B' — a classic exam bug to spot.

EXACT VALUES → SWITCHbreak, or you fall through
switch (day) { case 6: case 7: System.out.println("Weekend!"); break; default: System.out.println("Working day"); }

Miss a break and execution falls through into the next case — sometimes a bug, here (6 and 7 sharing) a feature. "Predict the output with missing breaks" is a repeat question.

THE == TRAP AGAINif (x = 5) won't compile

In C this compiles and is always true — a legendary bug. Java refuses: incompatible types: int cannot be converted to boolean. Another small "robust" story for the buzzword chapter.

CHUNK 17 / 44≈ 8 MIN

Loops — three shapes, one chooser question, and labelled break.

All loops repeat; they differ only in what you know before starting. Know the count → for. Know only the condition → while. Must run at least once (menus!) → do-while. Plus the two escape hatches:

KNOWN COUNTfor
for (int i = 1; i <= 5; i++) System.out.println("Attempt " + i);

init → test → body → update → test… The test runs BEFORE each pass: for(;false;) runs zero times.

UNKNOWN COUNTwhile
while (balance > 0) { balance -= spend(); }

May run zero times. Forget to change balance inside → infinite loop, the #1 lab freeze.

AT LEAST ONCEdo-while
do { choice = showMenu(); } while (choice != 0); // only exception: while rides the closer

Body first, test after — guaranteed one pass. The differentiate-while-vs-do-while 2-marker lives on this single sentence.

ESCAPE HATCHESbreak leaves · continue skips
outer: for (int r = 0; r < 3; r++) for (int c = 0; c < 3; c++) if (found(r,c)) break outer;

Plain break exits only the INNER loop. A labelled break exits the named one — Java's civilised replacement for C's goto.

The chooser, one line each: for = "I know how many times." while = "I know when to stop." do-while = "run first, ask later." Write those three lines in any differentiate question and dress each with its example above — full marks.

CHUNK 18 / 44≈ 8 MIN

Drill — the UPI PIN gate. Everything from M3+M4 in one real program.

Your phone gives you three PIN attempts, then locks. That's a do-while (must ask at least once), an if/else (match?), a counter, and a break — every tool from the last two modules, in the order you'd actually build it:

UpiPinGate.java — COMPLETE & RUNNABLE
1import java.util.Scanner;
2public class UpiPinGate
3{
4 public static void main(String[] args)
5 {
6 Scanner sc = new Scanner(System.in);
7 final int CORRECT_PIN = 4271; // final: unchangeable — full story in M11
8 int attempts = 0;
9 boolean unlocked = false;
10 do // must ask at least once → do-while
11 {
12 System.out.print("Enter UPI PIN: ");
13 int entered = sc.nextInt();
14 attempts++;
15 if (entered == CORRECT_PIN) // == compares; = would not compile
16 {
17 unlocked = true;
18 break; // success — leave immediately
19 }
20 System.out.println("Wrong. Attempts left: " + (3 - attempts));
21 } while (attempts < 3); // do-while: the condition rides the closer
22 System.out.println(unlocked ? "✓ Payment screen unlocked" : "✗ LOCKED — try after 24h"); // ternary
23 }
24}
TERMINAL — RUN 1: WRONG × 3
$ java UpiPinGate
Enter UPI PIN: 1234
Wrong. Attempts left: 2
Enter UPI PIN: 1111
Wrong. Attempts left: 1
Enter UPI PIN: 0000
Wrong. Attempts left: 0
✗ LOCKED — try after 24h
RUN 2 (PIN 4271 on attempt 2): break fires on line 18, the loop exits early, ternary prints "✓ Payment screen unlocked". Trace it yourself — every line number is known.
Count the tools: Scanner (ch12) · final constant (M11 preview) · do-while (ch17) · == vs = (ch16) · break (ch17) · ternary (ch14) · int/boolean (ch9–10). Seven concepts, twenty-four lines, one program you already fully understand. That feeling is the point of this drill.
CHECKPOINT · MODULE 4

Can you hand-trace 2 + 3 * 4 > 10 && true, compute 12 & 10, explain >> vs >>> on a negative, pick the right loop in one sentence, and rebuild the PIN gate's skeleton? Then Modules 1–4 (the DESCRIBE half of the unit) are done — the JVM story starts next.

MODULE 5 / 123 CHUNKS · ≈ 24 MIN

THE JAVA STORY & THE TWELVE BUZZWORDS

Why Java exists — and the classic 6-mark buzzwords answer.

You've now compiled programs and watched crashes refuse to corrupt memory. Perfect timing: the buzzwords are no longer vocabulary to memorise — you've experienced half of them first-hand. This module turns your experience into a complete 6-mark model answer.

CHUNK 19 / 44≈ 7 MIN

1991, a set-top box, and the problem C couldn't solve.

James Gosling's team at Sun Microsystems was writing software for TV set-top boxes — dozens of different chips, one codebase. C compiles to one specific CPU's machine code, so every new chip meant recompiling, re-testing, re-shipping everything. Their fix became Java's whole identity: compile once to a fake, universal CPU's instructions (bytecode), then put a translator (the JVM) on every real device.

STEP 1You write Billing.java

Plain text, human-readable, CPU-agnostic — the same file forever.

STEP 2javacBilling.class

Bytecode: instructions for an imaginary, standardised CPU that no factory has ever manufactured. Compiled once.

STEP 3A JVM on every device

Windows JVM, Linux JVM, Mac JVM, Android's cousin — each translates the SAME bytecode to ITS machine's real instructions.

THE SLOGANWORA — Write Once, Run Anywhere

The .class file you made in chunk 5 would run unchanged on a Mac, a Linux server, a Raspberry Pi. The PLATFORM-SPECIFIC part is the JVM; your bytecode is platform-FREE.

✓ SOURCE (ONCE) → BYTECODE (ONCE) → ANY JVM (EVERYWHERE). THAT ARROW CHAIN IS THE "PLATFORM INDEPENDENCE" DIAGRAM PAPERS ASK YOU TO DRAW.

Timeline in one breath: 1991 project "Oak" (named after a tree outside Gosling's window) → renamed Java (the coffee) → 1995 public release riding the web boom → today: Android apps, banking backends, and your Unit 1. The exam only ever wants: Gosling, Sun Microsystems, 1991–1995, Oak → Java, WORA.

CHUNK 20 / 44≈ 8 MIN

Twelve buzzwords — each one a scene you've already lived.

Sun's marketing sheet listed Java's promises as one-word "buzzwords". Don't memorise definitions — attach each word to a scene. Eight of the twelve you have personally witnessed in the last nineteen chunks:

BUZZWORDTHE SCENE THAT PROVES IT
SimpleNo pointers, no manual memory freeing, no multiple inheritance headaches — C++'s sharpest knives removed. You never once called free().
Object-OrientedEverything lives in a class — even HelloWorld needed one. Modules 1–2 were this word.
Platform-Independent / PortableChunk 19's whole story: bytecode + a JVM per device = WORA. Also chunk 9: int is 32 bits on EVERY machine.
RobustChunk 13: marks[5] crashed with a precise message instead of corrupting memory. Chunk 16: if (x = 5) refused to compile. Java fails LOUDLY and EARLY.
SecureBytecode runs inside the JVM's sandbox — it can't directly poke the machine's memory or bypass the verifier. Untrusted code stays caged.
Interpreted + High-PerformanceThe JVM interprets bytecode — but its JIT compiler (next module) turns hot code into native speed. Both words, one machine.
MultithreadedOne program, many workers: your music app downloads, plays and animates simultaneously. Built into the language (Unit 4's star).
DistributedNetworking is in the standard library — Java programs on different machines talk over the internet as easily as calling a method.
Architecture-NeutralThe .class format commits to NO CPU brand — the "imaginary CPU" of chunk 19, stated formally.
DynamicClasses load at run time, on demand — a running program can even load classes it has never seen before.
The pairing trick examiners use:

Portable vs Architecture-Neutral — neutral says bytecode favours no CPU; portable adds that sizes/behaviour are identical everywhere. Interpreted vs High-Performance — they look contradictory until you name the JIT. If you can separate those two pairs, you're above the curve.

CHUNK 21 / 44 · MODEL Q≈ 9 MIN · NOTEBOOK FIRST

The classic 6-marker: six buzzwords, explained. Notebook first, then compare.

Buzzword questions are a fixture of this exam's style — but be honest about provenance: this exact wording is NOT from a released paper, so it is labelled what it is: a model question in past-paper shape. Pick the six you can prove with scenes. The model below chooses the six with the strongest one-line evidence, then anchors them with a runnable program.

MODEL QUESTION · PYQ-STYLE — NOT FROM A RELEASED PAPER 6 MARKSUNIT IREVISIT: CHUNKS 19–20
Model · 6m

Q. Explain any six Java buzzwords with suitable justification. [6 M]

MODEL ANSWER — 1 MARK PER BUZZWORD: NAME IT, DEFINE IT, PROVE IT · ONE PER PRESS ↓

1

Simple: Java removed C++'s hardest features — no pointers, no manual memory management, no operator overloading — so programmers make fewer catastrophic mistakes.✓ 1

2

Object-Oriented: all code lives inside classes; data and its operations travel together — even the smallest program declares a class.✓ 1

3

Platform-Independent (Portable): javac produces bytecode for the JVM, not machine code for one CPU; the same .class file runs on Windows, Linux and Mac — Write Once, Run Anywhere.✓ 1

4

Robust: strong typing catches errors at compile time and runtime checks (e.g. array bounds) stop bad code with a clear exception instead of corrupting memory.✓ 1

5

Secure: bytecode is verified before running and executes inside the JVM sandbox, unable to touch raw memory — safe even for code downloaded from a network.✓ 1

6

Multithreaded: the language has built-in support for many tasks in one program — download, play and display at once — without OS-specific code.✓ 1

Exam craft: the rubric is name + meaning + one concrete justification per word. A bare list of six names scores 2/6 at best. Close with the program below — evidence beats adjectives.

Six words × (name + meaning + proof) = 6/6. Model program seals it ↓

The model program: one file that demonstrates platform independence, robustness and object-orientation — cite it in your answer as "for example:"

HelloWORA.java — COMPLETE & RUNNABLE MODEL PROGRAM
1// One source file → one bytecode file → every OS. Compiled on Windows, run on Linux below.
2public class HelloWORA // object-oriented: code must live in a class
3{
4 public static void main(String[] args)
5 {
6 String os = System.getProperty("os.name"); // ask the JVM where we are
7 System.out.println("Same bytecode, now running on: " + os);
8 int[] safe = new int[2];
9 System.out.println("Robust: bounds are checked — safe[2] would throw, never corrupt.");
10 }
11}
TERMINAL — SAME .class, TWO MACHINES
C:\> javac HelloWORA.java
C:\> java HelloWORA
Same bytecode, now running on: Windows 11
Robust: bounds are checked — safe[2] would throw, never corrupt.
$ java HelloWORA  # same .class copied to Linux — NO recompile
Same bytecode, now running on: Linux
Robust: bounds are checked — safe[2] would throw, never corrupt.
One javac, two javas, zero changes — WORA demonstrated, not just claimed. In the exam, sketching this two-terminal run next to your six points is the difference between good and unforgettable.
CHECKPOINT · MODULE 5

Recite: Gosling · Sun · Oak→Java · 1995 · WORA. Then name six buzzwords with one-line proof each — out loud, no peeking. If you can, the classic 6-marker is banked.

MODULE 6 / 123 CHUNKS · ≈ 23 MIN

JVM & EXECUTION — INSIDE THE MACHINE THAT RUNS YOUR BYTECODE

Open the JVM's front door and walk through its rooms.

"Explain the JVM architecture" and "Is Java compiled or interpreted?" are both classic exam staples. Both are answered by one walk-through: what happens between java HelloWorld and the first line of output.

CHUNK 22 / 44≈ 8 MIN

The rooms: class loader, verifier, and the memory areas.

Think of the JVM as a secure office building your .class file must pass through. One room per press — this walk IS the architecture diagram, in order:

ROOM 1 · RECEPTIONClass Loader

Finds HelloWorld.class on disk and brings it in — on demand, at run time (there's the buzzword "dynamic"). Classes it never needs are never loaded.

ROOM 2 · SECURITYBytecode Verifier

Frisks every instruction BEFORE execution: no forged references, no stack tricks, no jumping outside the code. Fail = rejected, never run (buzzword "secure").

ROOM 3 · SHARED SHELVESMethod Area

One copy of each loaded class's structure — the code of methods, and the static variables (chunk 10's single shared copy lives HERE).

ROOM 4 · THE WAREHOUSEHeap

Every object new ever makes goes here — chunk 4's printed tickets, chunk 10's two CanteenCounters. Shared by all threads; patrolled by the garbage collector.

ROOM 5 · DESKSStacks (one per thread)

Each method call gets a frame holding its local variables (chunk 10's bill lived and died in one). Method returns → frame torn off instantly.

ROOM 6 · ENGINE HALLExecution Engine

Interpreter + JIT compiler + garbage collector — the trio that actually runs your program. They get the whole next chunk.

✓ LOADER → VERIFIER → METHOD AREA / HEAP / STACKS → EXECUTION ENGINE. DRAW SIX BOXES WITH ARROWS IN THIS ORDER = THE ARCHITECTURE DIAGRAM, FULL MARKS.

Memory mnemonic: classes on the shelves (method area), objects in the warehouse (heap), calls on the desk (stack). Where does each of chunk 10's variables live? totalOrders → shelves. studentName (×2) → warehouse. bill → desk. If that mapping is instant, Module 8's deep dive will feel like revision.

CHUNK 23 / 44≈ 8 MIN

The engine hall: interpreter, JIT, and the janitor.

Three workers share the engine hall, and each one resolves an apparent contradiction from the buzzword list:

WORKER 1The Interpreter — starts instantly

Reads bytecode one instruction at a time and performs it. Zero warm-up, but every repeat of a loop is re-translated — like a human interpreter re-translating the same sentence 10,000 times.

WORKER 2The JIT compiler — spots the hot spots

Watches what the interpreter runs. Code that repeats a lot ("hot" — say, a loop run 10,000×) gets compiled Just In Time into REAL machine code for THIS CPU, then reused at native speed. That's how "interpreted" and "high-performance" are both true.

WORKER 3The Garbage Collector — the janitor

Patrols the heap for objects no reference can reach any more and reclaims their memory automatically. You never call free(); whole categories of C bugs (leaks, double-free, dangling pointers) cannot exist. Full story with a runnable program: chunk 32.

QUESTION PAPERS ASKTHE ONE-LINE ANSWER
Interpreter vs JIT?Interpreter translates every time, line by line (fast start); JIT compiles hot code once to native (fast forever after).
Why is GC part of "robust"?Memory freeing is automatic and correct — the programmer cannot forget to free or free twice.
JDK vs JRE vs JVM?JVM runs bytecode · JRE = JVM + libraries (enough to RUN) · JDK = JRE + javac and tools (enough to DEVELOP). Nested like dolls: JDK ⊃ JRE ⊃ JVM.
CHUNK 24 / 44≈ 7 MIN

"Is Java compiled or interpreted?" — the answer that wins the mark.

The trap in this classic question is answering with one word. The full-marks answer is "both, in two stages" — and now you can narrate the stages from experience:

STAGE 1 · COMPILE TIMEjavac: source → bytecode

You did this in chunk 5. A real compilation — syntax checked, types checked, .class produced. But the target is the virtual machine, not your CPU.

STAGE 2 · RUN TIMEJVM: interpret + JIT

Bytecode is interpreted instruction-by-instruction, while the JIT compiles hot paths to native machine code mid-run.

THE CONTRASTC is one-stage; Python is (classically) zero-compile

C: compiled straight to one CPU's machine code — fast but platform-locked. Python: interpreted from source. Java deliberately sits between: compiled for portability, JIT-ed for speed.

✓ MODEL SENTENCE: "JAVA IS BOTH — javac COMPILES SOURCE TO BYTECODE ONCE; THE JVM THEN INTERPRETS IT AND JIT-COMPILES HOT SECTIONS TO NATIVE CODE AT RUN TIME."

SELF-CHECK · MODULES 5–6 · ANSWER BEFORE UNLOCKING

  1. Which room stops a tampered .class file, and when?
  2. Where exactly does static int totalOrders live? And a local int bill?
  3. Your friend claims "Java is slow because it's interpreted." Correct them in two sentences.
  4. You only need to RUN a .class file someone gave you. JDK, JRE or JVM — what's the minimum install?
Check honestly:
  1. The bytecode verifier — after loading, BEFORE a single instruction executes.
  2. totalOrdersmethod area (one copy with the class). bill → a stack frame of the call that created it.
  3. Only the FIRST passes of code are interpreted. The JIT compiles hot sections to native machine code at run time, so long-running Java approaches C speed — that's the "high-performance" buzzword.
  4. JRE (JVM alone has no standard libraries; JDK adds compilers you don't need just to run).
CHECKPOINT · MODULE 6

Draw the six rooms from memory with arrows, name the three engine-hall workers, and say the "both, two stages" sentence. That's the entire JVM exam surface. Halfway point of the course — the writing-classes half begins now.

MODULE 7 / 124 CHUNKS · ≈ 35 MIN

YOUR FIRST REAL CLASS — FIELDS, METHODS, CONSTRUCTORS, this, OVERLOADING

Build one class properly, and every later class is a variation.

One example thread runs through this module: a MetroCard. We give it state, behaviour, a proper birth ritual (constructors), self-awareness (this), and multiple front doors (overloading). Each chunk upgrades the same file — exactly how real classes grow.

CHUNK 25 / 44≈ 9 MIN

Fields hold the state, methods guard the rules.

A metro card knows two things (owner, balance) and does two things (recharge, ride). Note what the methods add: the ride method refuses when balance is short — the data can't be pushed into an illegal state, because behaviour guards it. That's Module 1's "cure" actually coded.

MetroCard.java — v1 · COMPLETE & RUNNABLE
1public class MetroCard
2{
3 String owner; // state: instance fields —
4 double balance; // every card gets its own copies
5 void recharge(double amount)
6 {
7 balance += amount;
8 System.out.println(owner + " recharged. Balance: ₹" + balance);
9 }
10 void ride(double fare)
11 {
12 if (fare > balance) // the method GUARDS the state
13 {
14 System.out.println("✗ Gate closed — insufficient balance");
15 return; // leave early; balance untouched
16 }
17 balance -= fare;
18 System.out.println("✓ Gate open. Remaining: ₹" + balance);
19 }
20 public static void main(String[] args)
21 {
22 MetroCard card = new MetroCard();
23 card.owner = "Ananya";
24 card.recharge(100);
25 card.ride(35);
26 card.ride(80); // only ₹65 left — watch the guard fire
27 }
28}
TERMINAL — THE REAL RUN
$ javac MetroCard.java && java MetroCard
Ananya recharged. Balance: ₹100.0
✓ Gate open. Remaining: ₹65.0
✗ Gate closed — insufficient balance
The third call did NOT subtract — the guard on line 12 returned early. State + the rules protecting it, in one unit: that is a class earning its keep.
Method anatomy, once and forever: void ride(double fare) = return type (void: gives nothing back) · name · parameter list. A method that ANSWERS instead of printing would be:
double getBalance() { return balance; }
— callers receive the value: double b = card.getBalance();. Parameters are local variables (chunk 10) born at the call, dead at return.
CHUNK 26 / 44≈ 9 MIN

Constructors — objects born valid, never assembled by hand.

v1 has a flaw: between new MetroCard() and setting the owner, the card exists half-built (owner is null). A constructor fixes birth itself: it runs automatically at new, its name equals the class name, and it declares no return type — not even void.

RULE 1Name = class name, no return type
MetroCard(String owner) { ... }

Write void MetroCard(...) and it silently becomes an ordinary method that never runs at birth — a vicious trick question.

RULE 2The free default — until you write one

Write no constructor and Java gifts MetroCard() {}. Write ANY constructor and the gift is withdrawn: new MetroCard() stops compiling. The #1 constructor exam trap.

RULE 3Overloadable, like methods

Several constructors with different parameter lists = several valid ways to be born. Java picks by the arguments at new.

MetroCard.java — v2 · CONSTRUCTOR UPGRADE (RUNNABLE)
1public class MetroCard
2{
3 String owner; double balance;
4 MetroCard(String ownerName, double openingBalance) // runs AT new
5 {
6 owner = ownerName;
7 balance = openingBalance;
8 System.out.println("Card issued to " + owner + " with ₹" + balance);
9 }
10 public static void main(String[] args)
11 {
12 MetroCard c1 = new MetroCard("Ananya", 100); // born complete
13 MetroCard c2 = new MetroCard("Farhan", 250);
14 // MetroCard c3 = new MetroCard(); ← would NOT compile now (rule 2!)
15 }
16}
TERMINAL — THE REAL RUN
$ javac MetroCard.java && java MetroCard
Card issued to Ananya with ₹100.0
Card issued to Farhan with ₹250.0
Nobody CALLED the constructor — new did, automatically, once per object. Uncomment line 14 and javac answers: "constructor MetroCard in class MetroCard cannot be applied to given types" — the free default is gone.
Constructor vs method — the 2-mark table: name must equal class name vs any name · no return type (not even void) vs must declare one · invoked automatically by new vs called explicitly · runs exactly once per object vs any number of times.
CHUNK 27 / 44≈ 8 MIN

this — the object's own name for itself, and constructor chaining.

Real code names constructor parameters the SAME as the fields (owner, not ownerName) — cleaner APIs, but now owner = owner; would assign the parameter to itself. this breaks the tie: this.owner is always the field.

USE 1 · TIE-BREAKERthis.field = parameter
MetroCard(String owner, double balance) { this.owner = owner; this.balance = balance; }

Inside any instance method, this is a reference to the object the call was made onc1.ride(35) makes this mean c1.

USE 2 · CHAININGthis(...) — one constructor calls another
MetroCard(String owner) { this(owner, 50); // reuse the 2-arg one; ₹50 default }

No duplicated setup logic. Hard rule: this(...) must be the first statement of the constructor — anything before it is a compile error.

THE TRAPthis inside static? Never.

this means "the current object" — but static methods run with NO object (chunk 6). Using this in mainnon-static variable this cannot be referenced from a static context. Now that famous error message finally makes sense.

Say it once, own it: this.x = the field · this(…) = my other constructor · this alone = me, this object. Three spellings, one keyword, two guaranteed marks.

CHUNK 28 / 44 · ADD-ON≈ 9 MIN

Overloading — one name, many doors. Plus: when should a method be static?

Overloading = same method name, different parameter lists, same class. The compiler picks the version by the arguments you pass — decided fully at compile time (remember that phrase; Module 10 contrasts it with overriding's run-time decision).

OVERLOAD BY COUNTrecharge() vs recharge(amt)
void recharge() // quick top-up { balance += 100; } void recharge(double amt) { balance += amt; }
OVERLOAD BY TYPEfind(int) vs find(String)

Look a card up by number OR by owner name — same verb, different key. You've used overloading all course: println(int), println(String), println(double)

NOT OVERLOADINGReturn type alone changes nothing
int total() { ... } double total() // ✗ compile error — same parameter list { ... }

The call total() gives the compiler no way to choose. Parameter lists must differ — the definition papers test.

And the add-on decision every class forces: should this method be static? One test, three verdicts — one per press:

THE TEST"Does it need a particular object's fields?"

YES → instance method. NO (works only on its inputs) → static. That single question decides every case below.

VERDICT: INSTANCEride(fare)

Needs this card's balance — meaningless without asking WHICH card. Instance. Call: c1.ride(35).

VERDICT: STATICfareBetween("Ameerpet","Hitec")

Same answer for every card in the city — no card's fields involved. Static. Call: MetroCard.fareBetween(...) — on the class, no object needed. Same logic as Math.sqrt(25): you never write new Math().

THE COMPILER ENFORCES ITStatic methods can't touch instance fields

Put balance += 10; inside a static method → non-static variable balance cannot be referenced from a static context. Same error as this in main, same reason: no object exists to own the field.

✓ NEEDS A PARTICULAR OBJECT'S DATA → INSTANCE. PURE INPUT→OUTPUT → STATIC. main() IS STATIC PRECISELY BECAUSE NO OBJECT EXISTS YET.

CHECKPOINT · MODULE 7

From memory: sketch MetroCard with two fields, a guarded method, a constructor using this, and one overload pair. Then answer: why can't a static method use this? If both flow, you can write any class Unit 1 asks for.

MODULE 8 / 124 CHUNKS + ADD-ON · ≈ 44 MIN

STATIC & MEMORY — WHERE EVERYTHING ACTUALLY LIVES AND DIES

The mental X-ray: see your program's memory while it runs.

Four chunks that turn "it just works" into "I know exactly where that variable is". This module powers every predict-the-output question — and quietly pre-answers half of Unit 2.

CHUNK 29 / 44≈ 9 MIN

static — the noticeboard the whole class shares.

Chunk 10 showed static counting across objects; now make it yours. Instance field = each student's own notebook. Static field = the classroom noticeboard — one copy, everyone reads and writes the same one. Watch a shared counter issue card numbers:

LibraryCard.java — COMPLETE & RUNNABLE
1public class LibraryCard
2{
3 static int cardsIssued = 0; // noticeboard: ONE copy, class-wide
4 String member; // notebook: one per object
5 int cardNo;
6 LibraryCard(String member)
7 {
8 this.member = member; // this = tie-breaker (chunk 27)
9 cardsIssued++; // bump the SHARED counter…
10 this.cardNo = cardsIssued; // …and copy it into MY notebook
11 }
12 public static void main(String[] args)
13 {
14 LibraryCard a = new LibraryCard("Ishita");
15 LibraryCard b = new LibraryCard("Rahul");
16 LibraryCard c = new LibraryCard("Zoya");
17 System.out.println(c.member + " holds card #" + c.cardNo);
18 System.out.println("Total issued: " + LibraryCard.cardsIssued); // via CLASS name
19 }
20}
TERMINAL — THE REAL RUN
$ javac LibraryCard.java && java LibraryCard
Zoya holds card #3
Total issued: 3
Three constructors each bumped the SAME cardsIssued (1→2→3); each object photocopied the current value into its own cardNo. Noticeboard + notebooks, cooperating.
Access rule (and the style marks it earns): statics belong to the class, so write LibraryCard.cardsIssued — not c.cardsIssued, which compiles but lies to the reader about ownership. Statics exist even with ZERO objects: Math.PI, Integer.MAX_VALUE — noticeboards of classes you never instantiate.
CHUNK 29+ · ADD-ON≈ 9 MIN

The static trio — variable · block · method, and exactly when each fires.

You've met the static variable (the noticeboard) and the static method (chunk 28's Math.sqrt logic). The missing sibling is the static block — a chunk of setup code that runs once, when the class loads, before anything else — even before main. One press each, then watch all three fire in order:

MEMBER 1static variable — one copy, class-wide
static int tokensServed = 0;

Lives in the method area from class-load to program-end. The noticeboard of chunk 29 — no revision needed, just its formal place in the trio.

MEMBER 2static block — runs at CLASS LOAD, once
static { // one-time setup — before main! }

No name, no call — the JVM runs it the moment the class loads. Use: computing a static value that needs more than one line (loading config, filling a lookup table). Several blocks? They run top-to-bottom.

MEMBER 3static method — callable with no object
static int nextToken() { return ++tokensServed; }

May touch ONLY static members — no instance fields, no this (chunk 28's test). Called on the class: TokenCounter.nextToken().

THE FIRING ORDERload → static vars → static blocks → main

The class loads once; static variables initialise and static blocks run in source order, exactly once — then, and only then, does main begin. "Predict which line prints first" questions are built on this order.

✓ VARIABLE = ONE SHARED COPY · BLOCK = ONE-TIME SETUP AT CLASS LOAD · METHOD = CLASS-LEVEL BEHAVIOUR. ALL THREE EXIST BEFORE ANY OBJECT DOES.

TokenCounter.java — COMPLETE & RUNNABLE
1public class TokenCounter
2{
3 static int tokensServed; // static VARIABLE — one shared copy
4 static String counterName;
5 static // static BLOCK — no name, runs at class load
6 {
7 counterName = "Counter-A";
8 tokensServed = 100; // tokens resume from yesterday's 100
9 System.out.println("① static block: " + counterName + " ready at token " + tokensServed);
10 }
11 static int nextToken() // static METHOD — no object needed
12 {
13 return ++tokensServed; // may touch ONLY static members
14 }
15 public static void main(String[] args)
16 {
17 System.out.println("② main begins"); // prints AFTER the block — always
18 System.out.println("③ serving token " + TokenCounter.nextToken());
19 System.out.println("④ serving token " + TokenCounter.nextToken()); // zero objects created!
20 }
21}
TERMINAL — THE REAL RUN
$ javac TokenCounter.java && java TokenCounter
① static block: Counter-A ready at token 100
② main begins
③ serving token 101
④ serving token 102
① printed BEFORE main's ② — the static block ran at class load, exactly once. Then the static method served 101 and 102 off the shared variable, with not a single object in sight. The whole program is class-level machinery.
The trio in one exam table: static variable — state, one copy, lives class-load→program-end · static block — setup, runs once at class load, before main, top-to-bottom if several · static method — behaviour, called on the class, can use only static members, no this. And the trick question: "can a static block print before main?" — it MUST; class loading always precedes main's first line.
Two static-block traps worth marks:

① A static block cannot use this or instance fields — same "no object exists" logic as main (chunk 6, chunk 27). ② Don't confuse it with an instance initializer block (braces WITHOUT the word static) — that one runs per-new, before the constructor, not at class load. "static block vs instance block vs constructor — order of execution?" is the classic differentiator: static block (once) → instance block (per object) → constructor (per object).

CHUNK 30 / 44≈ 9 MIN

Pass-by-value and the aliasing surprise — Java's most misunderstood rule.

"Can a method change my variable?" has a two-part answer that separates toppers from the crowd. Java is always pass-by-value — the method gets a photocopy. The twist: for objects, what's photocopied is the reference (the address), so both copies point at the same object.

CASE 1 · PRIMITIVEPhotocopy of the VALUE
static void bump(int x) { x++; } int marks = 80; bump(marks); // marks is STILL 80

The method bumped its own copy and threw it away. The caller's variable is untouchable.

CASE 2 · OBJECTPhotocopy of the ADDRESS
static void reward(MetroCard m) { m.balance += 50; // same object! } // caller's card DID gain ₹50

Two references, one heap object — changes through either are visible through both. This is aliasing.

CASE 3 · REASSIGNMENTBut re-pointing the copy does nothing
static void swapCard(MetroCard m) { m = new MetroCard("X", 0); } // caller still holds the ORIGINAL

The method re-aimed its own photocopy of the address. The caller's reference never moved — proof it was pass-by-VALUE all along.

✓ THE EXAM SENTENCE: "JAVA IS ALWAYS PASS-BY-VALUE; FOR OBJECTS, THE VALUE PASSED IS A COPY OF THE REFERENCE — SO MEMBERS CAN BE MUTATED, BUT THE CALLER'S REFERENCE CAN NEVER BE REDIRECTED."

Aliasing without any method — the 2-line trap:

MetroCard c2 = c1; copies the ADDRESS, not the card — one object, two names. c2.balance = 0; empties c1's balance too. "How many objects exist?" after such lines is a classic 1-marker: count the news, never the variable names.

CHUNK 31 / 44≈ 8 MIN

The full memory X-ray — one program, every region labelled.

Module 6 named the rooms; now furnish them with a real moment. Freeze LibraryCard (chunk 29) at line 13, just as Zoya's constructor runs, and place every value — one region per press:

METHOD AREA · SHELVESClass structure + statics

The LibraryCard class definition, the bytecode of its methods, and cardsIssued = 2→3 — exactly one copy, loaded once.

HEAP · WAREHOUSEThree objects, each self-contained

Object #1 {member="Ishita", cardNo=1} · #2 {member="Rahul", cardNo=2} · #3 {member="Zoya", cardNo=…being set}. Each has its OWN member and cardNo — no sharing.

STACK · DESKTwo frames, newest on top

Bottom: main's frame — references a, b, c (addresses aiming into the heap). Top: the running constructor's frame — parameter member and this (aimed at object #3).

THE MOTIONConstructor returns → its frame vanishes

Instantly, not eventually. The heap objects SURVIVE — they outlive the call that made them, reachable through main's references. Stack cleans itself; the heap needs a janitor…

✓ REFERENCES LIVE ON THE STACK, OBJECTS ON THE HEAP, CLASSES + STATICS IN THE METHOD AREA. EVERY "WHERE IS x STORED?" QUESTION IS NOW A LOOKUP.

Why this X-ray earns real money: stack frames die automatically — that's why locals need no GC. Heap objects can outlive everything — that's exactly why the garbage collector must exist. You've just derived the next chunk instead of memorising it.

CHUNK 32 / 44≈ 9 MIN

Garbage collection, witnessed — one runnable program, one final constant.

An object dies when no reference can reach it. This program makes an object unreachable on purpose, then politely asks the janitor to sweep — and Java proves the sweep happened by running the object's last rites (finalize):

GcWitness.java — COMPLETE & RUNNABLE
1public class GcWitness
2{
3 static final int MAX_SESSIONS = 2; // final: fixed at birth, ALL CAPS by convention
4 String sessionUser;
5 GcWitness(String user)
6 {
7 this.sessionUser = user;
8 }
9 protected void finalize() // the object's last words, spoken by GC
10 {
11 System.out.println("♻ collected session of " + sessionUser);
12 }
13 public static void main(String[] args)
14 {
15 GcWitness s1 = new GcWitness("guest_412");
16 GcWitness s2 = new GcWitness("admin");
17 s1 = null; // guest_412 now UNREACHABLE — eligible for GC
18 System.gc(); // a REQUEST, never a command
19 System.out.println("still alive: " + s2.sessionUser + " | limit " + MAX_SESSIONS);
20 // MAX_SESSIONS = 5; ← uncomment → "cannot assign a value to final variable"
21 }
22}
TERMINAL — THE REAL RUN
$ javac GcWitness.java && java GcWitness
♻ collected session of guest_412
still alive: admin | limit 2
guest_412 was swept (unreachable after line 17); admin survived (s2 still points at it). Order may vary and the sweep may even be skipped — System.gc() is a hint, which is itself an exam point.
The four GC sentences worth marks: ① eligibility = unreachability, not "not used lately" · ② System.gc() requests, never guarantees · ③ GC frees YOU from free() — the "robust" buzzword's strongest proof · ④ setting a reference to null kills the reference, and the object only if that was its last one. Plus the cameo: final made MAX_SESSIONS unchangeable — Module 11 opens all three of final's gates.
CHECKPOINT · MODULE 8

Test yourself: noticeboard-vs-notebook in one line, the static trio's firing order (block at class load → before main, always), the pass-by-value exam sentence, the three-region X-ray of any program, and GC's four sentences. Eight modules down — inheritance, the marks core, starts now.

MODULE 9 / 124 CHUNKS · ≈ 34 MIN

INHERITANCE — THE MARKS CORE OPENS

Write the common parts once. Let children add the rest.

From here to the end of the course, five of the six verified sheet PYQs land. Inheritance is the mechanism they all stand on: a child class receives everything its parent has, then extends it. The IS-A test from chunk 8 finally cashes in.

CHUNK 33 / 44≈ 9 MIN

extends — one keyword, everything inherited.

A food-delivery app has riders and customer-support agents. Both are staff: both have a name and an ID, both can clock in. Only the rider has a bike and delivers. Write the common part once in Staff; let Rider extend it:

StaffDemo.java — COMPLETE & RUNNABLE
1class Staff // the PARENT (superclass)
2{
3 String name; int id;
4 void clockIn()
5 {
6 System.out.println(name + " (#" + id + ") clocked in");
7 }
8}
9class Rider extends Staff // the CHILD — inherits name, id, clockIn()
10{
11 String bikeNo; // plus its OWN additions
12 void deliver()
13 {
14 System.out.println(name + " delivering on " + bikeNo); // uses INHERITED name!
15 }
16}
17public class StaffDemo
18{
19 public static void main(String[] args)
20 {
21 Rider r = new Rider();
22 r.name = "Kiran"; r.id = 207; r.bikeNo = "TS09 EA 4321";
23 r.clockIn(); // inherited — Rider never wrote it
24 r.deliver(); // its own
25 }
26}
TERMINAL — THE REAL RUN
$ javac StaffDemo.java && java StaffDemo
Kiran (#207) clocked in
Kiran delivering on TS09 EA 4321
Rider's body declares ONE field and ONE method — yet a Rider object carries name, id, clockIn(), bikeNo and deliver(). Everything flows down; nothing flows up (a Staff object has no deliver()).
Vocabulary that must be automatic: Staff = superclass / parent / base; Rider = subclass / child / derived. Direction check (chunk 8): "a Rider IS A Staff" ✓. What does NOT flow down: constructors (each class writes its own — next-next chunk) and private members (inherited in memory but not accessible by name — the fine print papers probe).
CHUNK 34 / 44≈ 8 MIN

The five shapes — and the diamond Java refuses to build.

Every inheritance question names one of five shapes. One per press — for each: the shape, a one-line example, and whether Java's class allows it:

SHAPE 1Single — A → B

Rider extends Staff. One parent, one child. The atom every other shape is built from. ✓ Allowed.

SHAPE 2Multilevel — A → B → C

Staff → Rider → EliteRider: a chain. EliteRider inherits from BOTH ancestors — grandchild gets everything. ✓ Allowed.

SHAPE 3Hierarchical — one parent, many children

Staff → Rider, Staff → SupportAgent, Staff → Chef. The most common shape in real systems. ✓ Allowed.

SHAPE 4Multiple — TWO parents, one child ✗

class Robot extends Machine, Workerrefused at compile time. Java classes may extend exactly ONE class. Why → the diamond, next press.

THE DIAMONDThe reason for the refusal

If Machine and Worker BOTH define start(), which one does Robot inherit? Ambiguity with no right answer — C++ allows it and suffers; Java bans it at the door. (Interfaces reopen this door safely — chunk 44.)

SHAPE 5Hybrid — any mix of the above

Hierarchical + multilevel in one tree, etc. Allowed exactly as long as no multiple-class inheritance hides inside it.

✓ SINGLE · MULTILEVEL · HIERARCHICAL = YES. MULTIPLE (OF CLASSES) = NO, BECAUSE OF THE DIAMOND. HYBRID = YES IF NO MULTIPLE INSIDE.

The sentence that upgrades your answer: "Java omits multiple inheritance of classes to avoid the diamond ambiguity, but delivers its benefits safely through interfaces (a class may implement many)." That one line connects three chunks and reads like a textbook author wrote it.

CHUNK 35 / 44 · PYQ≈ 8 MIN · NOTEBOOK FIRST

PYQ: define inheritance — sheet + runnable model program.

Everything needed landed in the last two chunks. Notebook first — then compare against the sheet and its model program.

PAST PAPER · PAPER 2 · QUESTION 2 2 MARKSUNIT IREVISIT: CHUNKS 33–34
P2 · Q2 · 2m

Q2. Define inheritance. [2 M]

MODEL ANSWER — DEFINITION + EXAMPLE + JAVA'S POSITION · ONE PER PRESS ↓

1

Definition: inheritance is the mechanism by which one class (the subclass) acquires the fields and methods of another (the superclass) using the extends keyword — the child reuses and extends the parent, modelling an IS-A relationship.✓ 1

2

Example + Java's stance: class Rider extends Staff — Rider inherits name, id and clockIn() and adds its own members. Java supports single, multilevel and hierarchical inheritance of classes; multiple inheritance of classes is NOT supported (diamond ambiguity — chunk 34).✓ 1

Exam craft: a 2-mark "define" wants definition + one concrete example. Naming the supported shapes and "Java achieves multiple inheritance's effect via interfaces" is the polish that makes 2/2 certain.

Definition + example + Java's stance. ✓ 2/2

The model program — single inheritance compiling and running, multiple inheritance left in as a comment with the exact compiler refusal it would trigger:

InheritKinds.java — COMPLETE & RUNNABLE MODEL PROGRAM
1class Machine
2{
3 void powerOn()
4 {
5 System.out.println("Machine powered on");
6 }
7}
8class Drone extends Machine // SINGLE inheritance ✓ one parent
9{
10 void fly()
11 {
12 System.out.println("Drone airborne");
13 }
14}
15// class Robot extends Machine, Worker {} // MULTIPLE ✗ — javac refuses:
16// error: '{' expected — Java stops parsing at the comma. One class, one parent.
17public class InheritKinds
18{
19 public static void main(String[] args)
20 {
21 Drone d = new Drone();
22 d.powerOn(); // inherited from the ONE parent
23 d.fly(); // its own
24 }
25}
TERMINAL — THE REAL RUN
$ javac InheritKinds.java && java InheritKinds
Machine powered on
Drone airborne
Single inheritance: compiles, runs, inherits. Uncomment line 15 and compilation dies instantly — the ban is enforced by the parser itself, before any semantic check.
In the exam: for a 2-marker, the two definitions + examples are enough. If it appears as a 4–6 marker ("explain types of inheritance"), add chunk 34's five shapes and this program as your evidence.
CHUNK 36 / 44≈ 9 MIN

super — the child's phone line to its parent. And who constructs first.

Constructors don't inherit — so how does a Rider's name get set properly? The child calls up: super(...) runs the parent's constructor, and the rule is iron — the parent is always fully built first. Watch the order:

BuildOrder.java — COMPLETE & RUNNABLE
1class Staff
2{
3 String name;
4 Staff(String name)
5 {
6 this.name = name;
7 System.out.println("1️⃣ Staff built for " + name);
8 }
9}
10class Rider extends Staff
11{
12 String bikeNo;
13 Rider(String name, String bikeNo)
14 {
15 super(name); // MUST be first statement — parent first
16 this.bikeNo = bikeNo;
17 System.out.println("2️⃣ Rider extras added: " + bikeNo);
18 }
19}
20public class BuildOrder
21{
22 public static void main(String[] args)
23 {
24 new Rider("Kiran", "TS09 EA 4321");
25 }
26}
TERMINAL — THE REAL RUN
$ javac BuildOrder.java && java BuildOrder
1️⃣ Staff built for Kiran
2️⃣ Rider extras added: TS09 EA 4321
Parent's message ALWAYS prints first. Even if you omit super(...), Java silently inserts super() — which fails to compile here because Staff has no no-arg constructor (chunk 26's withdrawn gift, striking again).
super's three spellings (mirror of this, chunk 27): super(...) = parent's constructor, first line only · super.method() = parent's version of a method I've overridden (meets its moment next module) · super.field = parent's field when mine shadows it. "Predict the print order" of a 3-level chain (A→B→C prints A, B, C) is a classic 2-marker — the rule is simply top of the family tree first.
CHECKPOINT · MODULE 9

Verify: extends in one sentence, the five shapes with the diamond reason, P2·Q2's definition + example, and the parent-first build order. Next module: the same family tree starts behaving differently per member — polymorphism, the unit's crown.

MODULE 10 / 124 CHUNKS · ≈ 36 MIN

POLYMORPHISM — ONE CALL, MANY BEHAVIOURS

The unit's crown: three PYQs in four chunks.

Overriding lets a child replace an inherited behaviour; dynamic dispatch lets one line of code pick the right replacement at run time. Together they carry more Unit-1 marks than any other topic — and all three sheet questions in this module are verified past-paper questions (P1·Q2 · P2·Q16a · P2·Q11b).

CHUNK 37 / 44≈ 9 MIN

Overriding — same signature, new body. @Override is your seatbelt.

Every Staff clocks in — but a Rider clocks in at a hub, not at the office. The child needs its own body for the same method: redefining an inherited method with the same name and same parameter list is overriding. (Different parameter list? That's overloading — chunk 28. Hold that thought two chunks.)

ClockIn.java — COMPLETE & RUNNABLE
1class Staff
2{
3 void clockIn()
4 {
5 System.out.println("Clocked in at head office");
6 }
7}
8class Rider extends Staff
9{
10 @Override // the seatbelt — compiler VERIFIES this overrides
11 void clockIn() // SAME name, SAME parameters
12 {
13 super.clockIn(); // optional: reuse parent's part first
14 System.out.println("…then checked in at delivery hub");
15 }
16}
17public class ClockIn
18{
19 public static void main(String[] args)
20 {
21 new Staff().clockIn();
22 new Rider().clockIn(); // same call — the child's body answers
23 }
24}
TERMINAL — THE REAL RUN
$ javac ClockIn.java && java ClockIn
Clocked in at head office
Clocked in at head office
…then checked in at delivery hub
Line 21: parent's body. Line 22: the OVERRIDE ran — which itself reused the parent via super.clockIn() before adding its own line. Replace + optionally reuse: overriding in full.
Three override rules papers test: ① signature must match exactly (name + parameter types + order) · ② access may only stay or WIDEN (protected→public fine; public→private refuses to compile — the child must honour the parent's promises) · ③ static methods never override — a same-signature static in the child merely hides the parent's; no dispatch happens. And @Override: misspell the name and the compiler stops you instead of silently creating a useless overload — always wear the seatbelt.
CHUNK 38 / 44 · PYQ≈ 8 MIN · NOTEBOOK FIRST

PYQ: the signature trap — override or not? Sheet + a compile-refusal exhibit.

This question could not exist before you knew BOTH overloading (chunk 28) and overriding (chunk 37). Now it's a one-line kill. Notebook first:

PAST PAPER · PAPER 1 · QUESTION 2 2 MARKSUNIT IREVISIT: CHUNKS 28 + 37
P1 · Q2 · 2m

Q2. A subclass redefines a superclass method but changes the parameter list. Is this overriding? Justify. [2 M]

MODEL ANSWER — VERDICT, THEN JUSTIFICATION · ONE PER PRESS ↓

1

No — it is overloading, not overriding. Overriding demands the same name AND the same parameter list; a changed parameter list creates a new overload that merely happens to live in the subclass.✓ 1

2

Consequence (the justify mark): both methods now coexist — the parent's version is still inherited and callable. No replacement happened, so no run-time dispatch will ever choose between them; the compiler picks by arguments alone.✓ 1

Exam craft: the proof-word is @Override — stick it on the changed-signature method and javac itself refuses, as the model exhibit below shows. Citing that refusal is the strongest justification you can write.

Verdict + coexistence + the compiler as your witness. ✓ 2/2

The model exhibit — a complete file where @Override makes the compiler prove the answer (a compile-refusal is the intended output, per the question's own logic):

NotAnOverride.java — COMPLETE COMPILE-REFUSAL EXHIBIT
1class Printer
2{
3 void printCopies(int n)
4 {
5 System.out.println(n + " copies");
6 }
7}
8class ColorPrinter extends Printer
9{
10 @Override // claims "I am overriding" —
11 void printCopies(double n) // — but the parameter list CHANGED
12 {
13 System.out.println(n + " colour copies");
14 }
15}
TERMINAL — THE COMPILER TESTIFIES
$ javac NotAnOverride.java
NotAnOverride.java:10: error:
method does not override or implement
a method from a supertype
1 error
javac's own words: "does not override". Delete line 10 (@Override) and it compiles fine — as an OVERLOAD: ColorPrinter then has both printCopies(int) and printCopies(double). The compiler just wrote your justification for you.
The one-line memory hook: overLOADing = same name, different parameters, chosen at COMPILE time · overRIDing = same everything, chosen at RUN time. Who chooses at run time, and how? Next chunk.
CHUNK 39 / 44≈ 9 MIN

Dynamic dispatch — two judges, one doorbell, and the proof file.

The setup that makes polymorphism fire: a parent reference may hold a child object (IS-A allows it). Then two judges rule on every call — one at compile time, one at run time:

THE LEGAL SETUPStaff s = new Rider();

Legal because a Rider IS A Staff. The reference type (Staff) and the object's real type (Rider) now disagree — and that disagreement is the entire mechanism.

JUDGE 1 · COMPILER"May you call it at all?"

Checks the call against the reference type. s.clockIn() ✓ (Staff has it) · s.deliver() ✗ refuses to compile — the compiler only sees a Staff.

JUDGE 2 · JVM"WHOSE body runs?"

At run time, looks at the real object on the heap — a Rider — and runs the Rider's override. The reference type has no vote here.

THE DOORBELLSame button, different answerer

The button is the reference — everyone presses the same one. Who answers depends on who's actually home — the object. Same press, different behaviour, decided at the moment of the ring.

✓ REFERENCE TYPE DECIDES WHAT YOU MAY CALL · OBJECT TYPE DECIDES WHOSE BODY RUNS. THAT SENTENCE ALONE IS WORTH FOUR MARKS.

The proof file — one array, one loop, one call… two different pay slips:

Payroll.java — COMPLETE & RUNNABLE
1class Courier
2{
3 double pay(int parcels)
4 {
5 return parcels * 25.0; // standard rate
6 }
7}
8class NightCourier extends Courier
9{
10 @Override
11 double pay(int parcels)
12 {
13 return parcels * 25.0 + 200; // night allowance
14 }
15}
16public class Payroll
17{
18 public static void main(String[] args)
19 {
20 Courier[] shift = { new Courier(), new NightCourier() }; // array literal braces stay inline — values, not a block
21 for (Courier c : shift)
22 {
23 System.out.println(c.pay(10)); // ONE call — each object answers itself
24 }
25 }
26}
TERMINAL — ONE LINE, TWO ANSWERS
$ javac Payroll.java && java Payroll
250.0
450.0
Line 23 is ONE line of code, yet printed two results: 10×25 = 250 for the day courier; 10×25 + 200 = 450 for the night courier. Each object chose its own body at run time. That is dynamic dispatch, caught in the act.
Why it matters beyond marks: add a WeekendCourier tomorrow — the loop never changes. Code open to extension, closed to modification: the design principle every Java framework is built on, running in 26 lines on your screen.
CHUNK 40 / 44 · PYQ ×2≈ 10 MIN · NOTEBOOK FIRST

The two 4-markers: explain dispatch, then write the Vehicle/Car program.

Both heavyweight polymorphism PYQs, back to back — you now hold every piece. First the "explain" question:

PAST PAPER · PAPER 2 · QUESTION 16(a) 4 MARKSUNIT IREVISIT: CHUNK 39
P2 · Q16a · 4m

Q16(a). Explain dynamic method dispatch in Java with a suitable example. [4 M]

MODEL ANSWER — FOUR CLEAN POINTS, ONE MARK EACH · ONE PER PRESS ↓

1

Definition: dynamic method dispatch resolves a call to an overridden method at run time, based on the actual class of the object, not the type of the reference variable.✓ 1

2

The legal setup: a superclass reference may hold a subclass object (IS-A) — e.g. Courier c = new NightCourier();.✓ 1

3

The two judges: the compiler validates the call against the reference type; the JVM selects the body from the object's real class — so c.pay(10) runs the NightCourier override and returns 450.0, not 250.0.✓ 1

4

Why it matters: it IS Java's run-time polymorphism — one loop over a Courier[] pays every courier kind correctly, and new kinds can be added without touching the loop. Cite Payroll.java (chunk 39) as the suitable example — write it out; it is only 14 lines.✓ 1

Definition + setup + two judges + the payoff loop = 4/4.

And the "write a program" twin — the question names its own classes (Vehicle/Car), so we obey. Notebook first, honestly: write it, then step the model:

PAST PAPER · PAPER 2 · QUESTION 11(b) 4 MARKSUNIT IREVISIT: CHUNKS 37 + 39
P2 · Q11b · 4m

Q11(b). Write a Java program where class Car overrides the method start() of class Vehicle. Demonstrate the overridden method using a superclass reference. [4 M]

MARKS MAP — WHAT EACH PIECE OF THE PROGRAM EARNS · ONE PER PRESS ↓

1

Mark 1 — parent with the method: class Vehicle defining start().

2

Mark 2 — the override: class Car extends Vehicle redefining the same signature, sealed with @Override.

3

Mark 3 — THE demonstration the question demands: Vehicle v = new Car();a superclass reference holding the child. Miss this line and the "demonstrate using a superclass reference" half of the question is unanswered.

4

Mark 4 — the call + expected output: v.start() printing the CAR's message, with the output written under the program. Showing the output is part of the answer.

Four pieces, four marks — the model below is the full-marks script. ✓ 4/4

VehicleDemo.java — COMPLETE & RUNNABLE MODEL PROGRAM
1class Vehicle
2{
3 void start() // mark 1: the parent's method
4 {
5 System.out.println("Vehicle starting…");
6 }
7}
8class Car extends Vehicle
9{
10 @Override
11 void start() // mark 2: same signature, new body
12 {
13 System.out.println("Car starting with push button ✓");
14 }
15}
16public class VehicleDemo
17{
18 public static void main(String[] args)
19 {
20 Vehicle v = new Car(); // mark 3: superclass reference, child object
21 v.start(); // mark 4: dispatch picks the CAR's body
22 }
23}
TERMINAL — THE REAL RUN
$ javac VehicleDemo.java && java VehicleDemo
Car starting with push button ✓
The reference said Vehicle; the OBJECT said Car — and the Car's body ran. Write this output line under your program in the exam: it completes mark 4. (This same file returns in Lab 2, in Eclipse.)
Same skeleton, any costume: the examiner may swap Vehicle/Car for Animal/Dog or Shape/Circle — the four-mark map never changes: parent method → same-signature override → parent ref holding child → the call plus its output.
CHUNK 40+ · ADD-ON≈ 10 MIN

The dispatch fine print — casts, the shadowed field, and the return type that narrows.

Three companions of dynamic dispatch that predict-the-output questions lean on. Each is one idea, one micro-example, one verdict — press through them:

COMPANION 1aUpcast — free, silent, always safe
Courier c = new NightCourier(); // no bracket needed

Child → parent view. Every NightCourier IS a Courier, so the compiler needs no convincing. You have been upcasting since chunk 39's payroll array.

COMPANION 1bDowncast — bracketed, and a runtime GAMBLE
NightCourier n = (NightCourier) c; // you sign a waiver

Parent view → child view. The bracket silences the COMPILER only — if the heap object is not really a NightCourier, the run dies with ClassCastException. Guard it: if (c instanceof NightCourier) first, always.

COMPANION 2Fields never dispatch — they HIDE
class A { int x = 1; } class B extends A { int x = 2; } A a = new B(); // a.x is 1, NOT 2!

A child re-declaring a parent's field creates a SECOND box with the same name — the object carries both. Which box a read hits is decided by the reference type at compile time. Methods follow the object; fields follow the reference. The fix in real code: never re-declare — assign the inherited field instead.

COMPANION 3Covariant returns — an override may NARROW its return type
class Kitchen { Dish serve() {} } class DosaCorner extends Kitchen { @Override Dosa serve() {} }

Legal since Java 5, provided Dosa extends Dish. Why it exists: callers holding the child reference get the specific type back without a downcast — the language deleting Companion 1b's gamble wherever it can.

✓ UPCAST FREE · DOWNCAST BRACKETED + instanceof-GUARDED · FIELDS HIDE (NEVER OVERRIDE) · OVERRIDES MAY NARROW RETURNS. FOUR LINES, FOUR VERDICT QUESTIONS COVERED.

The three traps, as the examiner writes them:

"Does this compile?" — an unguarded downcast ALWAYS compiles; the crash (ClassCastException) is at run time. ② "What does a.x print?" — check the REFERENCE type, not the object, for fields. ③ "Is this a valid override?" — a changed return type is legal ONLY if it narrows to a subclass of the original; anything unrelated refuses to compile. Each of these is a one-line verdict once you hold the four-line summary above.

CHECKPOINT · MODULE 10

The crown is yours if: overloading-vs-overriding is one breath, the two-judges sentence is automatic, you can write VehicleDemo.java cold in under four minutes — and the add-on's four verdicts (upcast/downcast, hidden fields, covariant returns) are one line each. Three PYQs banked in this module alone. Two short modules to the finish line.

MODULE 11 / 122 CHUNKS · ≈ 15 MIN

final — THE THREE GATES THAT SAY "NO FURTHER"

One keyword, three doors it can lock.

You've met final twice already (the PIN constant in chunk 18, MAX_SESSIONS in chunk 32). Now the full picture — it locks three different things depending on where it stands, and one 2-mark PYQ asks exactly that.

CHUNK 41 / 44≈ 8 MIN

final variable · final method · final class — one per press.

GATE 1final variable — the value locks
final double GST_RATE = 0.18; GST_RATE = 0.20; // ✗ cannot assign

Assign once, then read-only forever — Java's constant. Convention: ALL_CAPS. Reassigning = cannot assign a value to final variable, at compile time.

GATE 2final method — the body locks
class PaymentGateway { final void verifyOtp() { ... } }

Children may inherit and USE it, but may never override it — security-critical steps stay exactly as written. Attempting = verifyOtp() cannot override… overridden method is final.

GATE 3final class — the family line locks
final class AadhaarId { ... } // class FakeId extends AadhaarId ✗

No child may EVER extend it. Real example: String is final — nobody can subclass it to forge "strings" that lie. Attempting = cannot inherit from final AadhaarId.

THE PATTERNEach gate locks the next lever of change

Variable → value can't change · method → behaviour can't be overridden · class → family can't grow. Same word, escalating reach. A final CLASS makes all its methods effectively final; a final METHOD says nothing about its class.

✓ VALUE · BODY · FAMILY LINE — THREE LOCKS, ONE KEYWORD. ALL THREE REFUSALS HAPPEN AT COMPILE TIME.

CHUNK 42 / 44 · PYQ≈ 7 MIN · NOTEBOOK FIRST

PYQ: the significance of final — sheet + one program showing all three gates.

PAST PAPER · PAPER 2 · QUESTION 1 2 MARKSUNIT IREVISIT: CHUNK 41
P2 · Q1 · 2m

Q1. What is the significance of the final keyword in Java? [2 M]

MODEL ANSWER — THE THREE USES, NAMED AND EXEMPLIFIED · ONE PER PRESS ↓

1

final variable: may be assigned exactly once — creates a constant, e.g. final double GST_RATE = 0.18;.✓ ½

2

final method: cannot be overridden by any subclass — protects critical behaviour from redefinition.✓ ½

3

final class: cannot be extended at all — e.g. java.lang.String is final for security and immutability.✓ 1

Exam craft: "significance" = all three contexts, each with its half-line example. Only writing "final makes constants" scores half. The String example is the polish examiners remember.

Three gates, three examples, one keyword. ✓ 2/2

The model program — all three gates in one runnable file, with the forbidden lines left in as comments carrying their exact compiler refusals:

FinalGates.java — COMPLETE & RUNNABLE MODEL PROGRAM
1final class TaxRules // GATE 3: nobody may extend this class
2{
3 static final double GST_RATE = 0.18; // GATE 1: the constant
4 final double taxOn(double amount) // GATE 2: body locked (redundant in a final class — stated for the exam)
5 {
6 return amount * GST_RATE;
7 }
8}
9// class LooseTaxRules extends TaxRules {} // ✗ cannot inherit from final TaxRules
10public class FinalGates
11{
12 public static void main(String[] args)
13 {
14 TaxRules rules = new TaxRules();
15 System.out.println("GST on ₹2500: ₹" + rules.taxOn(2500));
16 // TaxRules.GST_RATE = 0.20; // ✗ cannot assign a value to final variable GST_RATE
17 }
18}
TERMINAL — THE REAL RUN
$ javac FinalGates.java && java FinalGates
GST on ₹2500: ₹450.0
Runs clean. Uncomment line 9 or line 16 and javac refuses with exactly the messages in the comments — the three gates, holding.
final vs finally vs finalize — the tie-breaker trivia: final = this keyword (three gates) · finally = the always-runs block of try/catch (Unit 3) · finalize() = GC's last-rites method (chunk 32). Three similar words, three different worlds — a favourite 1-mark differentiator.
CHECKPOINT · MODULE 11

Say the three gates with one example each, and separate final/finally/finalize in one breath. Sixth PYQ banked. One module left.

MODULE 12 / 122 CHUNKS · ≈ 18 MIN

ABSTRACT CLASSES & INTERFACES — THE LAST TWO TOOLS

final said "no further". abstract says "you MUST go further".

The mirror image of Module 11: final forbids change; abstract demands completion. These two chunks close the Unit-1 syllabus.

CHUNK 43 / 44≈ 9 MIN

abstract — a class that refuses to be built, methods that demand bodies.

A payments app supports UPI, cards and wallets. "Payment" itself is a real concept with real shared code (validation, receipts) — but a bare "payment" that is no particular kind should never exist. abstract encodes exactly that:

PaymentDemo.java — COMPLETE & RUNNABLE
1abstract class Payment // cannot be instantiated — concept only
2{
3 double amount;
4 Payment(double amount) // children call it via super
5 {
6 this.amount = amount;
7 }
8 abstract void pay(); // NO body — every child MUST supply one
9 void receipt() // concrete: shared by all children as-is
10 {
11 System.out.println("Receipt: ₹" + amount + " received");
12 }
13}
14class UpiPayment extends Payment
15{
16 UpiPayment(double amt)
17 {
18 super(amt);
19 }
20 @Override
21 void pay() // the debt, paid
22 {
23 System.out.println("Paid ₹" + amount + " via UPI");
24 }
25}
26public class PaymentDemo
27{
28 public static void main(String[] args)
29 {
30 // Payment p = new Payment(100); // ✗ Payment is abstract; cannot be instantiated
31 Payment p = new UpiPayment(499); // abstract REFERENCE, concrete object ✓
32 p.pay(); // dispatch (M10!) picks UpiPayment's body
33 p.receipt(); // shared concrete method, inherited as-is
34 }
35}
TERMINAL — THE REAL RUN
$ javac PaymentDemo.java && java PaymentDemo
Paid ₹499.0 via UPI
Receipt: ₹499.0 received
Line 31 is the exam's favourite subtlety: you may DECLARE a Payment reference (and dispatch through it) — you just may never construct a bare Payment object.
The rules in four lines: ① abstract class = cannot be instantiated, CAN hold fields, constructors and concrete methods · ② abstract method = signature + semicolon, no body, allowed ONLY in abstract classes · ③ a child must implement ALL inherited abstract methods — or be declared abstract itself (the debt passes down) · ④ abstract + final together is a compile error: one demands children, the other forbids them. That contradiction is a beloved true/false.
CHUNK 44 / 44≈ 9 MIN

interface — a pure contract. And the diamond door reopens, safely.

Push abstraction to the limit — remove ALL state and ALL implementation — and you get an interface: a list of method signatures, nothing else. A class implements it by supplying every body. And the payoff: a class may implement MANY interfaces — multiple inheritance's benefits, without the diamond (contracts carry no bodies to clash).

SmartSpeaker.java — COMPLETE & RUNNABLE
1interface Playable
2{
3 void play(String song); // implicitly public abstract — pure contract
4}
5interface Chargeable
6{
7 void charge();
8}
9class SmartSpeaker implements Playable, Chargeable // TWO contracts — legal!
10{
11 public void play(String song) // must be public
12 {
13 System.out.println("Playing " + song);
14 }
15 public void charge()
16 {
17 System.out.println("Charging via USB-C");
18 }
19}
20public class SmartSpeakerDemo
21{
22 public static void main(String[] args)
23 {
24 Playable device = new SmartSpeaker(); // interface reference — dispatch works here too
25 device.play("Kalki theme");
26 if (device instanceof Chargeable) // ask the object what else it can do
27 {
28 ((Chargeable) device).charge(); // safe cast — instanceof said yes
29 }
30 }
31}
TERMINAL — THE REAL RUN
$ javac SmartSpeaker.java && java SmartSpeakerDemo
Playing Kalki theme
Charging via USB-C
One class, two contracts, both honoured. instanceof checked the object's real capabilities before casting — the safe pattern for crossing between interface views of one object.
abstract class vs interface — the closing 4-mark table: fields: any vs only public static final constants · methods: mix of abstract + concrete vs pure contract (classically) · constructors: yes vs never · inheritance: ONE abstract parent (extends) vs MANY interfaces (implements) · choose: shared code + family identity → abstract class; capability that cuts across families → interface. And instanceof: asks "is this object really a …?" at run time — the companion tool whenever references get more general than objects.
CHECKPOINT · MODULE 12 — SYLLABUS COMPLETE

All 44 chunks, all 6 verified sheet PYQs (plus the buzzwords model question), all add-on topics: done. Two stops remain — the one-screen recap, and the unit-end test that tells you the truth about your exam readiness.

FINISH LINE · 1 / 2≈ 8 MIN

RAPID RECAP — THE WHOLE UNIT ON ONE SCREEN

Forty-four chunks, compressed to the sentences worth marks.

Read this the night before the exam. Every line links back to its chunk — anything that doesn't feel obvious yet is a jump-click away.

TOPICTHE EXAM SENTENCEBACK TO
Need of OOPFour failures → four cures: scattered facts→class · sideways edits→encapsulation · duplication→one method · four totals→one truth.ch2·3
Class vs objectBlueprint vs instance; class holds no instance data, each new allocates its own copies on the heap.ch4
main()public (JVM must reach it) · static (no object exists yet) · void · main · String[] args.ch6
Keywords / identifiers~50 reserved lowercase words vs names you invent; digit can't lead; true/false/null are literals; case-sensitive.ch7
Primitives8 types; signed range = −2ⁿ⁻¹ to 2ⁿ⁻¹−1; int and double are the defaults; String is a class.ch9
3 variable kindsLocal (per call, NO default) · instance (per object) · static (one copy, class-wide) — placement decides.ch10
CastingWidening is a gift, narrowing is a waiver — and the waiver truncates: (int) 9.99 == 9; int÷int stays int.ch11
ArraysFixed size, index 0 first, last = length−1; out of bounds = runtime exception naming index, length, line. 2D = array of arrays; rows via .length, slots via [r].length; jagged rows born separately; for-each is bounds-proof.ch13·13+
OperatorsLadder: unary → */% → +− → relational → equality → && → || → =. && short-circuits; x++ uses-then-bumps.ch14
Bitwise12&10=8 · 12|10=14 · 12^10=6 · ~n=−n−1 · <<=×2 · >> keeps sign · >>> stuffs zeros (differs only on negatives).ch15
Control flowRanges→if-ladder (strictest first) · exact values→switch (break or fall through) · for/while/do-while = known count / known condition / at-least-once.ch16·17
Buzzwords 6MName + meaning + proof, six times. Strongest proofs: WORA pipeline, bounds-check crash, JVM sandbox.ch21
JVMLoader → verifier → method area/heap/stacks → engine (interpreter + JIT + GC). JDK ⊃ JRE ⊃ JVM.ch22·23
Compiled or interpreted?Both: javac compiles source→bytecode once; JVM interprets + JIT-compiles hot paths at run time.ch24
ConstructorsName = class, NO return type, runs at new; writing any constructor withdraws the free default.ch26
thisthis.x = field · this(…) = sibling constructor (first line only) · this alone = current object; illegal in static.ch27
OverloadingSame name, DIFFERENT parameter list, same class — resolved at COMPILE time; return type alone never counts.ch28
static membersNoticeboard vs notebooks; access via class name; static methods can't touch instance fields or this. Static BLOCK runs once at class load — before main; order: static block → instance block → constructor.ch29·29+
Pass-by-valueAlways a copy; for objects the copied thing is the reference — members mutable, caller's reference immovable.ch30
Memory + GCReferences on stack, objects on heap, classes+statics in method area; GC collects the unreachable; System.gc() only requests.ch31·32
Inheritanceextends = everything flows down (not constructors, not private-by-name); 5 shapes; multiple-of-classes banned → diamond.ch33·34
supersuper(…) first line, parent constructed FIRST, always; super.m() = parent's overridden version.ch36
Overriding + dispatchSame signature, new body, @Override seatbelt; reference type decides WHAT you may call, object type decides WHOSE body runs.ch37·39
Casts · hiding · covarianceUpcast free · downcast bracketed + instanceof-guarded (else ClassCastException) · fields HIDE, never override (reference type picks the box) · an override may NARROW its return type.40+
finalVariable→value locks · method→no override · class→no children (String!); ≠ finally ≠ finalize.ch41
abstract / interfaceabstract = incomplete on purpose, no instantiation, debt passes down; interface = pure contract, MANY implementable — the safe diamond.ch43·44
The 6 verified PYQsP1·Q1 need of OOP (3) · P1·Q2 signature trap (38) · P2·Q1 final (42) · P2·Q2 define inheritance (35) · P2·Q11b Vehicle/Car (40) · P2·Q16a dispatch (40) — plus the buzzwords 6M model question (21).
CHECKPOINT · RAPID RECAP

Read every row without a single "wait, what?" — that's the bar. Any hesitation: click through, 90 seconds, come back.

FINISH LINE · 2 / 2≈ 25 MIN · CLOSED BOOK

UNIT-END TEST — EXAM PATTERN, HONEST CONDITIONS

Twenty-five minutes. Notebook. No scrolling up.

Structured like the real paper: Section A shorts, Section B longs, one program. Write ALL answers before unlocking ANY solution — the unlock order is part of the discipline.

SECTION A · SHORT ANSWERS · 6 × 2M = 12M · ≈ 12 MIN

  1. State the need of OOP over procedural programming. [2M]
  2. Differentiate between a class and an object with an example. [2M]
  3. Predict the output, with reasons: int a = 7, b = 2; System.out.println(a / b); System.out.println(a % b); System.out.println(a / (double) b); [2M]
  4. What is the difference between >> and >>>? When do they give the same result? [2M]
  5. Why must main() be declared static? What happens if it isn't? [2M]
  6. What is the significance of the final keyword in Java? [2M]
Mark yourself — half marks for half answers:
  1. Any two failure→cure pairs: scattered data→classes keep data+operations together · open state→encapsulation · duplicated logic→one method · many versions of truth→one object, one truth. (Pairs, not just problems!)
  2. Class = blueprint, no instance memory; object = runtime instance via new, own field copies. Example pair required — e.g. Ticket / t1 = new Ticket().
  3. 3 (int÷int truncates) · 1 (remainder) · 3.5 (one operand double → real division). One mark for values, one for reasons.
  4. >> copies the sign bit (arithmetic); >>> fills with zeros (logical). Identical on non-negative numbers; differ on negatives.
  5. The JVM calls it before any object exists; static members are callable on the class itself. Without static: compiles, but run fails — Error: Main method not found style refusal.
  6. Three gates: final variable = constant (assign once) · final method = no override · final class = no children (e.g. String). All three needed for 2/2.

SECTION B · LONG ANSWER · 1 × 6M · ≈ 6 MIN

  1. Explain any six Java buzzwords with suitable justification. [6M]
Rubric: 1 mark per buzzword = name + meaning + one concrete proof.
  1. Full model: chunk 21's sheet. Strongest six: Simple (no pointers/free()) · Object-Oriented (all code in classes) · Platform-Independent (bytecode + JVM per device = WORA) · Robust (bounds check crashes cleanly; if(x=5) refused) · Secure (verifier + sandbox) · Multithreaded (built-in concurrent tasks). A bare six-name list ≈ 2/6 — the proofs carry the marks.

SECTION C · PROGRAM · 1 × 4M · ≈ 7 MIN

  1. Write a Java program where class Circle overrides the method area() of class Shape. Demonstrate the overridden method using a superclass reference, and show the expected output. [4M]
The four-mark map (chunk 40's skeleton, new costume — write it fully):
  1. M1: class Shape with a double area() method whose body is return 0; (or printing a generic line) — braces on their own lines, as always.
  2. M2: class Circle extends Shape with field double r;, a constructor, and an @Override double area() whose body is return 3.14159 * r * r; — same signature.
  3. M3: Shape s = new Circle(7); — the superclass reference the question demands.
  4. M4: System.out.println(s.area()); + the expected output written under the program (≈ 153.93791). Dispatch ran the Circle's body — say so in one closing line.

Under 4 minutes and compiles in your head? You are exam-ready. Anything shaky — its chunk is one click up.

FINAL CHECKPOINT · UNIT 1 COMPLETE

Scored 16+/22 honestly? Unit 1 is banked — revisit only your wrong answers' chunks. Below 16: the recap table names every weak row's chunk. Either way, you just did the whole unit in one sitting. Respect.