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.
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.
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.
Types, variables (all three kinds), casting, arrays, every operator, every branch and loop — the repeat short-answer factory.
Buzzwords (a 6-marker every paper), JVM rooms, JIT, your first class, static, memory, GC — where "explain" questions live.
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
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.
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.
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.
"Flat expenses" lives in four places at once. In code: the same real-world thing spread over unrelated variables in unrelated files.
Ask "what did we spend this month?" — four different totals. In code: every function computes its own version of the same answer.
"Record an expense" exists four ways — one per notebook. A bug fixed in one copy survives in the other three.
"How much on groceries?" — nobody can say, though every rupee was written down somewhere.
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.
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:
One named unit — ExpenseRegister — keeps the data AND the operations on it together. The thing itself finally exists in the program.
The register's pages aren't loose — state changes only through the register's own operations. Nobody scribbles sideways.
"Add expense" is written once, used by all four flatmates, and bug-fixed in exactly one place.
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.
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.)
Q1. State the need of OOP over procedural programming. [2 M]
MODEL ANSWER — ANY TWO PAIRS, FAILURE → WHAT OOP ADDED · ONE PER PRESS ↓
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
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
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.
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
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.
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.
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.
Declares what every ticket will have (fields) and what every ticket can do (methods).
new is the printing press — every press produces a fresh object with its own copies of the fields.
t1, t2, t3… all from class Ticket, each independent: changing t1.seat touches nobody else's seat.
That single sentence — with the word instance — is the phrase examiners scan for.
| CLASS | OBJECT |
|---|---|
| Blueprint / template — a logical description | Real, usable thing built from it — a physical reality in memory |
| Written once by the programmer | Created any number of times at runtime with new |
| Allocates no memory for instance data | Each 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.) | |
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.
// My first Java program — file name MUST be HelloWorld.javapublic class HelloWorld{ public static void main(String[] args) { System.out.println("Hello, World!"); System.out.println("Unit 1, I am coming for you."); }}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.① File saved as helloworld.java → class 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 HelloWorld → ClassNotFoundException. The run command takes the class name, not the file name.
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:
public — visible from outsideThe 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.
static — callable with no objectChicken-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.)
void — returns nothingWhen main ends, the program ends — there is nobody left to hand a return value to.
main — the agreed nameA contract, not a keyword. The JVM looks for exactly this spelling; Main or mian compiles fine and then fails at run time.
String[] args — the inboxAnything 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.
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.
| FAMILY | IN HelloWorld.java | THE RULE |
|---|---|---|
| Keywords | public 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 args | Names you chose. You could rename both and the program still runs identically. |
| Identifiers (library's) | String System out println | Also 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 keywords | true false null | Officially 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:
A letter, _ or $ — never a digit.
Letters, digits, _, $. No spaces, no hyphens, no other symbols.
Any keyword (or true/false/null) is off the table.
total, Total and TOTAL are three different identifiers. Convention (not law): ClassName, variableName, CONSTANT_NAME.
upiAmountLetters only, starts with a letter. Textbook camelCase.
_backupCopy & $rateUnderscore and dollar are valid first characters — legal, though conventions reserve them for special uses.
2ndSeatStarts with a digit — breaks Rule 1. Write seat2 or secondSeat.
ticket-priceHyphen is the minus operator — Java reads "ticket minus price". Use ticketPrice.
classKeyword — Rule 3. But Class1 or myClass? Perfectly legal.
x, a1, tempLegal — 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.
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:
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.
"A Car is an Engine" is nonsense — so no extends. The engine becomes a field inside the car.
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
- One sentence: what is an object, using the word instance?
- Your file is
hello.javabut the public class isHello. Compile, run, or fail — and with what message? - Why exactly must
mainbestatic? - Legal or illegal:
$total·new·o2Level·2gether? HospitalandDoctor: IS-A or HAS-A? AndDoctorandPerson?
- An object is an instance of a class — a runtime copy with its own field values, created by
new. - Compile fails: class Hello is public, should be declared in a file named Hello.java. Public class name and file name must match exactly.
- The JVM must call it before any object exists; static members are callable on the class itself, no object needed.
$totallegal ·newillegal (keyword) ·o2Levellegal (digit not first) ·2getherillegal (digit first).- Hospital HAS-A Doctor (a hospital is not a doctor). Doctor IS-A Person — inheritance direction:
Doctor extends Person.
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.
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.
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.
| TYPE | SIZE | RANGE / VALUES | YOU'D USE IT FOR |
|---|---|---|---|
byte | 8 bits | −128 to 127 | Raw file/network bytes |
short | 16 bits | −32,768 to 32,767 | Rare; legacy formats |
int | 32 bits | ≈ −2.14 × 10⁹ to 2.14 × 10⁹ | The default whole number — counts, seats, marks |
long | 64 bits | ≈ ±9.2 × 10¹⁸ | Phone numbers, timestamps, populations — write 98490L |
float | 32 bits | ~7 significant digits | Rare; must write 4.5f |
double | 64 bits | ~15 significant digits | The default decimal — prices, averages, percentages |
char | 16 bits | One Unicode character | 'A', '₹', 'అ' — single quotes |
boolean | JVM-dependent | true / false only | Flags — never 0/1 like C |
−2⁷ to 2⁷−1 = −128 to 127. Matches the table — the formula regenerates every signed row.
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.
String is a classCapital S, double quotes, has methods like .length(). Papers ask "list the primitive types" hoping you'll include String — don't.
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.
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?
public class CanteenCounter{ static int totalOrders = 0; // STATIC — one copy for the whole class String studentName; // INSTANCE — one copy per object void order(int items) { int bill = items * 40; // LOCAL — born and dies inside this call totalOrders++; System.out.println(studentName + " pays ₹" + bill + " | orders so far: " + totalOrders); } public static void main(String[] args) { CanteenCounter a = new CanteenCounter(); a.studentName = "Meera"; CanteenCounter b = new CanteenCounter(); b.studentName = "Vikram"; a.order(2); b.order(3); }}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".| KIND | DECLARED | COPIES | BORN → DIES | DEFAULT VALUE |
|---|---|---|---|---|
| Local | Inside a method | One per call | Method starts → method returns | NONE — using it uninitialised is a compile error |
| Instance | In class, no static | One per object | new → object garbage-collected | 0 / 0.0 / false / null, automatic |
| Static | In class, with static | Exactly one, ever | Class loads → program ends | 0 / 0.0 / false / null, automatic |
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.
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:
byte → short → int → long → float → double. No syntax needed.
Without the cast: compile error incompatible types: possible lossy conversion.
7 / 2 is 3, not 3.5int ÷ int stays int — the fraction is discarded before any assignment. Fix: make one side double: 7 / 2.0 → 3.5, or (double) 7 / 2.
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.
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:
import java.util.Scanner; // move 1: tell Java where Scanner livespublic class MessBill{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); // move 2: aim it at the keyboard System.out.print("Days ate in mess: "); int days = sc.nextInt(); // move 3: read, typed System.out.print("Rate per day: "); double rate = sc.nextDouble(); System.out.println("Mess bill: ₹" + (days * rate)); sc.close(); }}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.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:
Or with values: int[] m = {70, 82, 91, 65, 88};
Last valid index is always length − 1.
.length — no parenthesesArray .length vs String .length() — a beloved 1-mark trick.
public class MarksReport{ public static void main(String[] args) { int[] marks = {70, 82, 91, 65, 88}; // array literal — braces on one line are values, not a block int total = 0; for (int i = 0; i < marks.length; i++) // i < length, NEVER <= { total += marks[i]; } System.out.println("Average: " + (total / (double) marks.length)); // cast! chunk 11 System.out.println("Slot 5: " + marks[5]); // THE CRASH — there is no slot 5 }}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.
Size fixed at birth; every slot auto-defaults (0 / 0.0 / false / null — same table as instance fields, chunk 10).
Braces on ONE line here are values, not a block — the single place inline braces are house-legal. Only allowed at declaration.
new + literal — reusable anywhereSame result as style 2, but THIS form also works later: c = new int[]{9, 9}; — a bare {9, 9} after declaration refuses to compile.
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:
int[][] 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.
marks.length vs marks[0].lengthmarks.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.
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.
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.
public class ArraysTour{ public static void main(String[] args) { int[] a = new int[3]; // style 1: sized — 0,0,0 int[] b = {10, 20, 30}; // style 2: literal — values, not a block int[] c = new int[]{5, 15, 25}; // style 3: new + literal int d[] = {1, 2}; // style 4: C-style — legal, discouraged a[0] = 7; int sum = 0; for (int x : b) // for-each: no index, no bounds risk { sum += x; } System.out.println("sum of b = " + sum + " | c[2] = " + c[2] + " | d[1] = " + d[1]); int[][] marks = { {70, 82}, {91, 65} }; // 2D: an array OF arrays System.out.println("marks[1][0] = " + marks[1][0]); // row 1, slot 0 int[][] jagged = new int[3][]; // jagged: outer only — rows born separately jagged[0] = new int[1]; jagged[1] = new int[3]; jagged[2] = new int[2]; for (int r = 0; r < jagged.length; r++) // rows via .length… { System.out.println("row " + r + " holds " + jagged[r].length + " slots"); // …slots via [r].length } System.out.println("a[0] = " + a[0] + " | a[1] defaulted to " + a[1]); }}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.① 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).
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.
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.
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.
| FAMILY | OPERATORS | THE 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 |
| Ternary | cond ? yes : no | A one-line if-else that produces a value: String result = marks >= 40 ? "PASS" : "FAIL"; |
1. ++ -- ! (unary)
2. * / %
3. + −
4. < <= > >=
5. == !=
6. && then ||
7. = += (last, rightmost)
2 + 3 * 4 > 10 && true① 3*4=12 → ② 2+12=14 → ③ 14>10=true → ④ true&&true=true. Four steps, strictly by the ladder.
Parentheses beat everything and cost nothing. In exam answers, brackets also show the examiner your order — free partial marks even if arithmetic slips.
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):
| OP | NAME | RULE (per bit) | 12 op 10 → |
|---|---|---|---|
& | AND | 1 only if BOTH are 1 | 00001000 = 8 |
| | OR | 1 if EITHER is 1 | 00001110 = 14 |
^ | XOR | 1 only if they DIFFER | 00000110 = 6 |
~ | NOT (unary) | flip every bit | ~12 = −13 (always −n−1) |
<< | Left shift | shift left, fill 0s = × 2 per step | 12 << 2 = 48 |
>> | Signed right | shift right, copy the sign bit = ÷ 2 per step | 12 >> 2 = 3 · −12 >> 2 = −3 |
>>> | Unsigned right | shift right, always fill 0s | same on positives; −1 >>> 28 = 15 |
>> 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.
& vs &&& works on bits (and never short-circuits); && works on booleans and short-circuits. Same shape, different families.
File permissions (rwx = 3 bits), network headers, graphics — anywhere 32 booleans must fit in one int. x << 3 is also a famously fast ×8.
a ^ b ^ b == aXOR with the same value twice returns the original — the basis of simple encryption and the "find the odd one out" interview classic.
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:
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.
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.
if (x = 5) won't compileIn 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.
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:
forinit → test → body → update → test… The test runs BEFORE each pass: for(;false;) runs zero times.
whileMay run zero times. Forget to change balance inside → infinite loop, the #1 lab freeze.
do-whileBody first, test after — guaranteed one pass. The differentiate-while-vs-do-while 2-marker lives on this single sentence.
break leaves · continue skipsPlain 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.
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:
import java.util.Scanner;public class UpiPinGate{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); final int CORRECT_PIN = 4271; // final: unchangeable — full story in M11 int attempts = 0; boolean unlocked = false; do // must ask at least once → do-while { System.out.print("Enter UPI PIN: "); int entered = sc.nextInt(); attempts++; if (entered == CORRECT_PIN) // == compares; = would not compile { unlocked = true; break; // success — leave immediately } System.out.println("Wrong. Attempts left: " + (3 - attempts)); } while (attempts < 3); // do-while: the condition rides the closer System.out.println(unlocked ? "✓ Payment screen unlocked" : "✗ LOCKED — try after 24h"); // ternary }}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.
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.
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.
Billing.javaPlain text, human-readable, CPU-agnostic — the same file forever.
javac → Billing.classBytecode: instructions for an imaginary, standardised CPU that no factory has ever manufactured. Compiled once.
Windows JVM, Linux JVM, Mac JVM, Android's cousin — each translates the SAME bytecode to ITS machine's real instructions.
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.
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:
| BUZZWORD | THE SCENE THAT PROVES IT |
|---|---|
| Simple | No pointers, no manual memory freeing, no multiple inheritance headaches — C++'s sharpest knives removed. You never once called free(). |
| Object-Oriented | Everything lives in a class — even HelloWorld needed one. Modules 1–2 were this word. |
| Platform-Independent / Portable | Chunk 19's whole story: bytecode + a JVM per device = WORA. Also chunk 9: int is 32 bits on EVERY machine. |
| Robust | Chunk 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. |
| Secure | Bytecode 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-Performance | The JVM interprets bytecode — but its JIT compiler (next module) turns hot code into native speed. Both words, one machine. |
| Multithreaded | One program, many workers: your music app downloads, plays and animates simultaneously. Built into the language (Unit 4's star). |
| Distributed | Networking is in the standard library — Java programs on different machines talk over the internet as easily as calling a method. |
| Architecture-Neutral | The .class format commits to NO CPU brand — the "imaginary CPU" of chunk 19, stated formally. |
| Dynamic | Classes load at run time, on demand — a running program can even load classes it has never seen before. |
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.
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.
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 ↓
Simple: Java removed C++'s hardest features — no pointers, no manual memory management, no operator overloading — so programmers make fewer catastrophic mistakes.✓ 1
Object-Oriented: all code lives inside classes; data and its operations travel together — even the smallest program declares a class.✓ 1
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
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
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
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:"
// One source file → one bytecode file → every OS. Compiled on Windows, run on Linux below.public class HelloWORA // object-oriented: code must live in a class{ public static void main(String[] args) { String os = System.getProperty("os.name"); // ask the JVM where we are System.out.println("Same bytecode, now running on: " + os); int[] safe = new int[2]; System.out.println("Robust: bounds are checked — safe[2] would throw, never corrupt."); }}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.
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.
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:
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.
Frisks every instruction BEFORE execution: no forged references, no stack tricks, no jumping outside the code. Fail = rejected, never run (buzzword "secure").
One copy of each loaded class's structure — the code of methods, and the static variables (chunk 10's single shared copy lives HERE).
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.
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.
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.
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:
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.
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.
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 ASK | THE 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. |
"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:
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.
Bytecode is interpreted instruction-by-instruction, while the JIT compiles hot paths to native machine code mid-run.
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
- Which room stops a tampered .class file, and when?
- Where exactly does
static int totalOrderslive? And a localint bill? - Your friend claims "Java is slow because it's interpreted." Correct them in two sentences.
- You only need to RUN a .class file someone gave you. JDK, JRE or JVM — what's the minimum install?
- The bytecode verifier — after loading, BEFORE a single instruction executes.
totalOrders→ method area (one copy with the class).bill→ a stack frame of the call that created it.- 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.
- JRE (JVM alone has no standard libraries; JDK adds compilers you don't need just to run).
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.
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.
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.
public class MetroCard{ String owner; // state: instance fields — double balance; // every card gets its own copies void recharge(double amount) { balance += amount; System.out.println(owner + " recharged. Balance: ₹" + balance); } void ride(double fare) { if (fare > balance) // the method GUARDS the state { System.out.println("✗ Gate closed — insufficient balance"); return; // leave early; balance untouched } balance -= fare; System.out.println("✓ Gate open. Remaining: ₹" + balance); } public static void main(String[] args) { MetroCard card = new MetroCard(); card.owner = "Ananya"; card.recharge(100); card.ride(35); card.ride(80); // only ₹65 left — watch the guard fire }}void ride(double fare) = return type (void: gives nothing back) · name · parameter list. A method that ANSWERS instead of printing would be:double b = card.getBalance();. Parameters are local variables (chunk 10) born at the call, dead at return.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.
Write void MetroCard(...) and it silently becomes an ordinary method that never runs at birth — a vicious trick question.
Write no constructor and Java gifts MetroCard() {}. Write ANY constructor and the gift is withdrawn: new MetroCard() stops compiling. The #1 constructor exam trap.
Several constructors with different parameter lists = several valid ways to be born. Java picks by the arguments at new.
public class MetroCard{ String owner; double balance; MetroCard(String ownerName, double openingBalance) // runs AT new { owner = ownerName; balance = openingBalance; System.out.println("Card issued to " + owner + " with ₹" + balance); } public static void main(String[] args) { MetroCard c1 = new MetroCard("Ananya", 100); // born complete MetroCard c2 = new MetroCard("Farhan", 250); // MetroCard c3 = new MetroCard(); ← would NOT compile now (rule 2!) }}new vs called explicitly · runs exactly once per object vs any number of times.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.
this.field = parameterInside any instance method, this is a reference to the object the call was made on — c1.ride(35) makes this mean c1.
this(...) — one constructor calls anotherNo duplicated setup logic. Hard rule: this(...) must be the first statement of the constructor — anything before it is a compile error.
this inside static? Never.this means "the current object" — but static methods run with NO object (chunk 6). Using this in main → non-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.
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).
recharge() vs recharge(amt)find(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)…
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:
YES → instance method. NO (works only on its inputs) → static. That single question decides every case below.
ride(fare)Needs this card's balance — meaningless without asking WHICH card. Instance. Call: c1.ride(35).
fareBetween("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().
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.
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.
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.
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:
public class LibraryCard{ static int cardsIssued = 0; // noticeboard: ONE copy, class-wide String member; // notebook: one per object int cardNo; LibraryCard(String member) { this.member = member; // this = tie-breaker (chunk 27) cardsIssued++; // bump the SHARED counter… this.cardNo = cardsIssued; // …and copy it into MY notebook } public static void main(String[] args) { LibraryCard a = new LibraryCard("Ishita"); LibraryCard b = new LibraryCard("Rahul"); LibraryCard c = new LibraryCard("Zoya"); System.out.println(c.member + " holds card #" + c.cardNo); System.out.println("Total issued: " + LibraryCard.cardsIssued); // via CLASS name }}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.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:
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.
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.
May touch ONLY static members — no instance fields, no this (chunk 28's test). Called on the class: TokenCounter.nextToken().
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.
public class TokenCounter{ static int tokensServed; // static VARIABLE — one shared copy static String counterName; static // static BLOCK — no name, runs at class load { counterName = "Counter-A"; tokensServed = 100; // tokens resume from yesterday's 100 System.out.println("① static block: " + counterName + " ready at token " + tokensServed); } static int nextToken() // static METHOD — no object needed { return ++tokensServed; // may touch ONLY static members } public static void main(String[] args) { System.out.println("② main begins"); // prints AFTER the block — always System.out.println("③ serving token " + TokenCounter.nextToken()); System.out.println("④ serving token " + TokenCounter.nextToken()); // zero objects created! }}this. And the trick question: "can a static block print before main?" — it MUST; class loading always precedes main's first line.① 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).
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.
The method bumped its own copy and threw it away. The caller's variable is untouchable.
Two references, one heap object — changes through either are visible through both. This is aliasing.
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."
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.
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:
The LibraryCard class definition, the bytecode of its methods, and cardsIssued = 2→3 — exactly one copy, loaded once.
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.
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).
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.
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):
public class GcWitness{ static final int MAX_SESSIONS = 2; // final: fixed at birth, ALL CAPS by convention String sessionUser; GcWitness(String user) { this.sessionUser = user; } protected void finalize() // the object's last words, spoken by GC { System.out.println("♻ collected session of " + sessionUser); } public static void main(String[] args) { GcWitness s1 = new GcWitness("guest_412"); GcWitness s2 = new GcWitness("admin"); s1 = null; // guest_412 now UNREACHABLE — eligible for GC System.gc(); // a REQUEST, never a command System.out.println("still alive: " + s2.sessionUser + " | limit " + MAX_SESSIONS); // MAX_SESSIONS = 5; ← uncomment → "cannot assign a value to final variable" }}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.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.
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.
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:
class Staff // the PARENT (superclass){ String name; int id; void clockIn() { System.out.println(name + " (#" + id + ") clocked in"); }}class Rider extends Staff // the CHILD — inherits name, id, clockIn(){ String bikeNo; // plus its OWN additions void deliver() { System.out.println(name + " delivering on " + bikeNo); // uses INHERITED name! }}public class StaffDemo{ public static void main(String[] args) { Rider r = new Rider(); r.name = "Kiran"; r.id = 207; r.bikeNo = "TS09 EA 4321"; r.clockIn(); // inherited — Rider never wrote it r.deliver(); // its own }}private members (inherited in memory but not accessible by name — the fine print papers probe).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:
Rider extends Staff. One parent, one child. The atom every other shape is built from. ✓ Allowed.
Staff → Rider → EliteRider: a chain. EliteRider inherits from BOTH ancestors — grandchild gets everything. ✓ Allowed.
Staff → Rider, Staff → SupportAgent, Staff → Chef. The most common shape in real systems. ✓ Allowed.
class Robot extends Machine, Worker — refused at compile time. Java classes may extend exactly ONE class. Why → the diamond, next press.
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.)
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.
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.
Q2. Define inheritance. [2 M]
MODEL ANSWER — DEFINITION + EXAMPLE + JAVA'S POSITION · ONE PER PRESS ↓
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
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:
class Machine{ void powerOn() { System.out.println("Machine powered on"); }}class Drone extends Machine // SINGLE inheritance ✓ one parent{ void fly() { System.out.println("Drone airborne"); }}// class Robot extends Machine, Worker {} // MULTIPLE ✗ — javac refuses:// error: '{' expected — Java stops parsing at the comma. One class, one parent.public class InheritKinds{ public static void main(String[] args) { Drone d = new Drone(); d.powerOn(); // inherited from the ONE parent d.fly(); // its own }}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:
class Staff{ String name; Staff(String name) { this.name = name; System.out.println("1️⃣ Staff built for " + name); }}class Rider extends Staff{ String bikeNo; Rider(String name, String bikeNo) { super(name); // MUST be first statement — parent first this.bikeNo = bikeNo; System.out.println("2️⃣ Rider extras added: " + bikeNo); }}public class BuildOrder{ public static void main(String[] args) { new Rider("Kiran", "TS09 EA 4321"); }}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.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.
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).
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.)
class Staff{ void clockIn() { System.out.println("Clocked in at head office"); }}class Rider extends Staff{ @Override // the seatbelt — compiler VERIFIES this overrides void clockIn() // SAME name, SAME parameters { super.clockIn(); // optional: reuse parent's part first System.out.println("…then checked in at delivery hub"); }}public class ClockIn{ public static void main(String[] args) { new Staff().clockIn(); new Rider().clockIn(); // same call — the child's body answers }}@Override: misspell the name and the compiler stops you instead of silently creating a useless overload — always wear the seatbelt.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:
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 ↓
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
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):
class Printer{ void printCopies(int n) { System.out.println(n + " copies"); }}class ColorPrinter extends Printer{ @Override // claims "I am overriding" — void printCopies(double n) // — but the parameter list CHANGED { System.out.println(n + " colour copies"); }}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:
Staff 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.
Checks the call against the reference type. s.clockIn() ✓ (Staff has it) · s.deliver() ✗ refuses to compile — the compiler only sees a Staff.
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 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:
class Courier{ double pay(int parcels) { return parcels * 25.0; // standard rate }}class NightCourier extends Courier{ @Override double pay(int parcels) { return parcels * 25.0 + 200; // night allowance }}public class Payroll{ public static void main(String[] args) { Courier[] shift = { new Courier(), new NightCourier() }; // array literal braces stay inline — values, not a block for (Courier c : shift) { System.out.println(c.pay(10)); // ONE call — each object answers itself } }}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.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:
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 ↓
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
The legal setup: a superclass reference may hold a subclass object (IS-A) — e.g. Courier c = new NightCourier();.✓ 1
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
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:
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 ↓
Mark 1 — parent with the method: class Vehicle defining start().
Mark 2 — the override: class Car extends Vehicle redefining the same signature, sealed with @Override.
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.
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
class Vehicle{ void start() // mark 1: the parent's method { System.out.println("Vehicle starting…"); }}class Car extends Vehicle{ @Override void start() // mark 2: same signature, new body { System.out.println("Car starting with push button ✓"); }}public class VehicleDemo{ public static void main(String[] args) { Vehicle v = new Car(); // mark 3: superclass reference, child object v.start(); // mark 4: dispatch picks the CAR's body }}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:
Child → parent view. Every NightCourier IS a Courier, so the compiler needs no convincing. You have been upcasting since chunk 39's payroll array.
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.
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.
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.
① "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.
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.
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.
final variable · final method · final class — one per press.
final variable — the value locksAssign once, then read-only forever — Java's constant. Convention: ALL_CAPS. Reassigning = cannot assign a value to final variable, at compile time.
final method — the body locksChildren 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.
final class — the family line locksNo 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.
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.
PYQ: the significance of final — sheet + one program showing all three gates.
Q1. What is the significance of the final keyword in Java? [2 M]
MODEL ANSWER — THE THREE USES, NAMED AND EXEMPLIFIED · ONE PER PRESS ↓
final variable: may be assigned exactly once — creates a constant, e.g. final double GST_RATE = 0.18;.✓ ½
final method: cannot be overridden by any subclass — protects critical behaviour from redefinition.✓ ½
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:
final class TaxRules // GATE 3: nobody may extend this class{ static final double GST_RATE = 0.18; // GATE 1: the constant final double taxOn(double amount) // GATE 2: body locked (redundant in a final class — stated for the exam) { return amount * GST_RATE; }}// class LooseTaxRules extends TaxRules {} // ✗ cannot inherit from final TaxRulespublic class FinalGates{ public static void main(String[] args) { TaxRules rules = new TaxRules(); System.out.println("GST on ₹2500: ₹" + rules.taxOn(2500)); // TaxRules.GST_RATE = 0.20; // ✗ cannot assign a value to final variable GST_RATE }}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.Say the three gates with one example each, and separate final/finally/finalize in one breath. Sixth PYQ banked. One module left.
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.
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:
abstract class Payment // cannot be instantiated — concept only{ double amount; Payment(double amount) // children call it via super { this.amount = amount; } abstract void pay(); // NO body — every child MUST supply one void receipt() // concrete: shared by all children as-is { System.out.println("Receipt: ₹" + amount + " received"); }}class UpiPayment extends Payment{ UpiPayment(double amt) { super(amt); } @Override void pay() // the debt, paid { System.out.println("Paid ₹" + amount + " via UPI"); }}public class PaymentDemo{ public static void main(String[] args) { // Payment p = new Payment(100); // ✗ Payment is abstract; cannot be instantiated Payment p = new UpiPayment(499); // abstract REFERENCE, concrete object ✓ p.pay(); // dispatch (M10!) picks UpiPayment's body p.receipt(); // shared concrete method, inherited as-is }}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).
interface Playable{ void play(String song); // implicitly public abstract — pure contract}interface Chargeable{ void charge();}class SmartSpeaker implements Playable, Chargeable // TWO contracts — legal!{ public void play(String song) // must be public { System.out.println("Playing " + song); } public void charge() { System.out.println("Charging via USB-C"); }}public class SmartSpeakerDemo{ public static void main(String[] args) { Playable device = new SmartSpeaker(); // interface reference — dispatch works here too device.play("Kalki theme"); if (device instanceof Chargeable) // ask the object what else it can do { ((Chargeable) device).charge(); // safe cast — instanceof said yes } }}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.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.
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.
| TOPIC | THE EXAM SENTENCE | BACK TO |
|---|---|---|
| Need of OOP | Four failures → four cures: scattered facts→class · sideways edits→encapsulation · duplication→one method · four totals→one truth. | ch2·3 |
| Class vs object | Blueprint 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 |
| Primitives | 8 types; signed range = −2ⁿ⁻¹ to 2ⁿ⁻¹−1; int and double are the defaults; String is a class. | ch9 |
| 3 variable kinds | Local (per call, NO default) · instance (per object) · static (one copy, class-wide) — placement decides. | ch10 |
| Casting | Widening is a gift, narrowing is a waiver — and the waiver truncates: (int) 9.99 == 9; int÷int stays int. | ch11 |
| Arrays | Fixed 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+ |
| Operators | Ladder: unary → */% → +− → relational → equality → && → || → =. && short-circuits; x++ uses-then-bumps. | ch14 |
| Bitwise | 12&10=8 · 12|10=14 · 12^10=6 · ~n=−n−1 · <<=×2 · >> keeps sign · >>> stuffs zeros (differs only on negatives). | ch15 |
| Control flow | Ranges→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 6M | Name + meaning + proof, six times. Strongest proofs: WORA pipeline, bounds-check crash, JVM sandbox. | ch21 |
| JVM | Loader → 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 |
| Constructors | Name = class, NO return type, runs at new; writing any constructor withdraws the free default. | ch26 |
| this | this.x = field · this(…) = sibling constructor (first line only) · this alone = current object; illegal in static. | ch27 |
| Overloading | Same name, DIFFERENT parameter list, same class — resolved at COMPILE time; return type alone never counts. | ch28 |
| static members | Noticeboard 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-value | Always a copy; for objects the copied thing is the reference — members mutable, caller's reference immovable. | ch30 |
| Memory + GC | References on stack, objects on heap, classes+statics in method area; GC collects the unreachable; System.gc() only requests. | ch31·32 |
| Inheritance | extends = everything flows down (not constructors, not private-by-name); 5 shapes; multiple-of-classes banned → diamond. | ch33·34 |
| super | super(…) first line, parent constructed FIRST, always; super.m() = parent's overridden version. | ch36 |
| Overriding + dispatch | Same signature, new body, @Override seatbelt; reference type decides WHAT you may call, object type decides WHOSE body runs. | ch37·39 |
| Casts · hiding · covariance | Upcast free · downcast bracketed + instanceof-guarded (else ClassCastException) · fields HIDE, never override (reference type picks the box) · an override may NARROW its return type. | 40+ |
| final | Variable→value locks · method→no override · class→no children (String!); ≠ finally ≠ finalize. | ch41 |
| abstract / interface | abstract = incomplete on purpose, no instantiation, debt passes down; interface = pure contract, MANY implementable — the safe diamond. | ch43·44 |
| The 6 verified PYQs | P1·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). | — |
Read every row without a single "wait, what?" — that's the bar. Any hesitation: click through, 90 seconds, come back.
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
- State the need of OOP over procedural programming. [2M]
- Differentiate between a class and an object with an example. [2M]
- 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] - What is the difference between
>>and>>>? When do they give the same result? [2M] - Why must
main()be declaredstatic? What happens if it isn't? [2M] - What is the significance of the
finalkeyword in Java? [2M]
- 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!)
- Class = blueprint, no instance memory; object = runtime instance via
new, own field copies. Example pair required — e.g.Ticket/t1 = new Ticket(). - 3 (int÷int truncates) · 1 (remainder) · 3.5 (one operand double → real division). One mark for values, one for reasons.
>>copies the sign bit (arithmetic);>>>fills with zeros (logical). Identical on non-negative numbers; differ on negatives.- 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.
- 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
- Explain any six Java buzzwords with suitable justification. [6M]
- 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
- Write a Java program where class
Circleoverrides the methodarea()of classShape. Demonstrate the overridden method using a superclass reference, and show the expected output. [4M]
- M1:
class Shapewith adouble area()method whose body isreturn 0;(or printing a generic line) — braces on their own lines, as always. - M2:
class Circle extends Shapewith fielddouble r;, a constructor, and an@Override double area()whose body isreturn 3.14159 * r * r;— same signature. - M3:
Shape s = new Circle(7);— the superclass reference the question demands. - 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.
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.