Part B · Class 1 of 2 · Data in, decisions made — Java learns to listen
Your program finally
listens back.
HelloWorld only talks. Today the flatmates' programs start listening — Rohit types the mess bill in, Scanner catches it, a variable holds it, a data type says exactly what shape it is, and an array lines five of them up in one tray.
- readPull typed input into a running program with
Scanner— numbers with nextInt(), whole lines with nextLine(), and know which to use when. - classifyPlace any value on the eight-primitive shelf — size, range and default — and tell a primitive from a reference type in one sentence.
- debugCatch the two classic traps with your eyes: the nextLine() swallow after nextInt(), and integer division silently throwing away the paise.
- predictTrace a declaration, a cast and an array walk on paper and state the printed output before the program runs — the exam's favourite request.
- The eight primitives — sizes, ranges, defaults (before Scanner, deliberately)PYQ
- Scanner — import it, build it, ask it: nextInt()
- Worked example — read a number, print its square
- Worked example — read a full name with nextLine()TRAP
- Variable = a named box in memory · declaration vs initialisation
- Scope & lifetime — where the box exists, when it goes away
- Reference types — the box holds an address, not the thingPYQ
- Casting — widening flows free, narrowing spillsPYQ
- Activity 1 — predict the mess-bill split for 3 runsNOTEBOOK
- Activity 2 — the blank-name bug (nextLine swallow)NOTEBOOK
- Activity 3 — primitive or reference? Krish's library cardNOTEBOOK
- Arrays — the numbered tray · index boundsPYQ
- Worked example — Diya's marks tray, find the best subject
- Activity 4 — IS-A or HAS-A, six Hyderabad pairsNOTEBOOK
- Activity 5 — trace the champion loop pass by passNOTEBOOK
- Activity 6 — the off-by-one crash (i <= 5)NOTEBOOK
16 TOPICS · 4 BUILD-UPS · 6 CODE FILES · 6 ACTIVITIES · 3 HOMEWORK
PART 2 · THE SHELF COMES FIRST
Eight kinds of value. Know the shelf before you shop.
In a moment, Scanner.nextInt() will hand you an int — so you must know what an int is before you catch one. Java ships exactly eight primitive types: four for whole numbers, two for decimals, one for single characters, one for true/false. Build the shelf one box per press.
The definition first — write it exactly like this: a data type is a set of permissible values together with the legal operations on those values. boolean: permissible values {true, false}, legal operations logic only — you cannot add two booleans. int: whole numbers in its 4-byte range, with arithmetic and comparison. Every box on the shelf below is exactly this — one value-set, one operation-set. This sentence, verbatim, is the full-marks opening of every data-type answer.
BUILD-UP · ONE PRIMITIVE PER PRESS — WATCH THE SIZES DOUBLE
WHOLE NUMBERS · FOUR SIZES OF THE SAME IDEA
−128 to 127. Tiny — a spice box. Rarely typed, often stored.
default 0
−32,768 to 32,767. A lunchbox. Legacy files and old formats.
default 0
±2.1 billion, roughly. The everyday choice — roll numbers, headcounts, rupees.
default 0 · ★ TODAY'S WORKHORSE
±9.2 quintillion. Aadhaar numbers, milliseconds since 1970. Literal ends in L.
default 0L
DECIMALS · TWO PRECISIONS
~7 digits of precision. Literal ends in f: 3.14f.
default 0.0f
~15 digits. The default for decimals — bills, averages, percentages. Just write 840.50.
default 0.0 · ★ DECIMAL WORKHORSE
ONE CHARACTER · ONE TRUTH
A single character in single quotes: 'A', '₹'. Two bytes because Java speaks Unicode — Telugu included.
default '\u0000'
Only true or false. Is the bill paid? Is the room clean? (*size not strictly defined — JVM's business.)
default false
Why memorise sizes? Because the exam asks, and because overflow is real. "List the eight primitive data types of Java with their sizes and default values" is a standing short-answer question. Learn the shelf as 1-2-4-8 for whole numbers, 4-8 for decimals, 2 for char, 1 for truth — the doubling pattern carries you through.
String starts with a capital letter because it is a class, not a primitive — a sealed box from Class 2, holding many chars behind one door. That difference gets its own part today (reference types), and its full chapter at Class 25.
PART 3 · THE PIPELINE
Scanner — a reading machine bolted onto the keyboard.
The keyboard produces a stream of raw characters. Scanner is the machine that reads that stream and hands you typed values — an int when you ask for an int, a line when you ask for a line. Build the pipeline one station per press.
BUILD-UP · KEYBOARD, SYSTEM.IN, SCANNER, VARIABLE — ONE STATION PER PRESS
Rohit types 840 and presses Enter. Raw keystrokes, nothing more.
The standard input stream — a pipe of raw characters: '8' '4' '0' ⏎. Java can't add these yet.
The reading machine. nextInt() reads the characters and assembles a real int out of them.
A named box in memory now holds the value. From here on it's yours to split, compare, print.
Keyboard speaks characters. Your program needs values. Scanner is the translator. ✦
import java.util.Scanner; — the first line above the class. Scanner lives in the java.util cupboard; the import tells javac which cupboard to open.
Scanner sc = new Scanner(System.in); — stamp one Scanner object (Class 2's new!) and bolt it onto the keyboard stream.
int bill = sc.nextInt(); — the program pauses, waits for Rohit to type and press Enter, then hands the assembled int into the box.
Notice what just happened: your first useful object. sc is an instance of the Scanner class — facts (where to read from) and operations (nextInt(), nextLine(), nextDouble()) sealed in one box, exactly the picture from Class 2. You didn't write the Scanner class; you're using one Java wrote for you. That's the whole point of OOP — boxes you can reuse.
PART 4 · WORKED EXAMPLE 1
Square.java — the first program that answers back.
Twelve lines, typed by hand, Allman braces throughout. Watch it grow one line per press on the left; the command prompt on the right shows the whole conversation — including what Krish types in.
- Class
Square, saved asSquare.javainclass-03; importjava.util.Scanneron line 2. - Prompt with
print(notprintln) so typing happens on the same line:Enter a number: - Read one int with
nextInt(); printSquare =followed by n × n.
13 — program answers Square = 169.C:\Users\diya\Desktop\java-practice\class-03> javac Square.java
C:\Users\diya\Desktop\java-practice\class-03> java Square
Enter a number: 13 <- Krish types this
Square = 169
The program paused at line 9, waited for Krish, then answered. A conversation, not a monologue. ✦
print stays on the same line, so Krish types his 13 right after the colon. println would have pushed the cursor down first. Small tool, deliberate choice.
nextInt() blocks: the program stands still until Enter is pressed. Nothing is broken — it's listening. New programmers restart "frozen" programs that were simply waiting.
In "Square = " + n * n, the * runs first (169), then + glues text and number into one printed line. Full precedence rules arrive in Class 4.
PART 5 · WORKED EXAMPLE 2
Greet.java — reading words, not just numbers.
Names have spaces. next() reads one word and stops at the first space; nextLine() reads the whole line up to Enter. Diya's full name needs the second one — watch the difference matter.
next() would stop at the first space; this program must not.- Class
Greet, saved asGreet.javainclass-03; Scanner imported. - Prompt
Your full name:then read the WHOLE line withnextLine(). - Print one line:
Welcome,+ the full name +!
Diya Reddy — program answers Welcome, Diya Reddy! with the space kept (with next() it would wrongly say just Welcome, Diya!).C:\Users\diya\Desktop\java-practice\class-03> java Greet
Your full name: Diya Reddy
Welcome, Diya Reddy!
— had line 9 used sc.next() instead —
Welcome, Diya! <- "Reddy" left behind in the pipe
next() stops at the first space. nextLine() reads to the Enter key. Choose by what the value IS. ✦
Call nextInt() and then nextLine(), and the second one seems to read nothing. Why? nextInt() takes the digits but leaves the Enter key in the pipe — and nextLine() happily reads that leftover empty line. Activity 2 makes you fix exactly this bug; Lab 0 will name it again.
PART 6 · THE NAMED BOX
A variable is a named box in memory.
You've been using them since line 7 of Square.java. Now the precise words: a variable is a box in memory with a name, a type that fixes what may go in, and a scope that fixes where the name means anything.
int bill; — a box named bill, shaped for an int, exists from this line on. It holds nothing useful yet, and Java refuses to let you read it until you fill it.
bill = 840; — the first value lands. Usually both at once: int bill = 840;. Declare-then-read-before-filling is a compile error, not a silent zero (that mercy is for fields, later).
A variable exists from its declaration to the closing brace of the block it was born in. Born inside main's braces means gone at main's }. Outside those braces, the name means nothing.
Flat analogy, one line: a variable is a labelled dabba in the flat's kitchen. The label is the name, the dabba's shape is the type (a chutney jar won't take a full biryani), and the scope is the kitchen itself — walk out of the flat and shouting "bill!" gets you nothing. Lifetime: the dabba is washed and gone when the block's } closes.
Declaring int n twice in one block is a compile error: variable n is already defined. One box, one label, one block. Shadowing across nested blocks is a subtler story — parked for the self-study sheet.
STILL PART 6 · WHAT MAY THE LABEL SAY? · IDENTIFIERS
The label on the box has rules — and a reserved list you can't touch.
Every name you invent — for a variable, a class, a method — is an identifier. Java accepts almost anything, with four hard rules and one polite convention.
(1) Letters, digits, _ and $ only — no spaces, no -. (2) Never start with a digit: bill2 yes, 2bill no. (3) Never a keyword: int int; is refused. (4) Case matters: bill, Bill and BILL are three different boxes.
Variables and methods start lowercase and hump the rest: busFare, printCard (camelCase). Classes start with a capital: Greet, Scanner. Constants shout: MAX_MARKS. The compiler doesn't force it — every reader expects it.
int a1$_x = 840; compiles. So does int x;. Neither tells the next reader what the box holds. int busFare = 840; is the same box wearing an honest label — name the MEANING, not the type.
STILL PART 6 · THE RESERVED LIST · KEYWORDS, GROUPED BY JOB
Fifty words belong to Java itself. Grouped, they stop being a list to memorise.
A keyword is a word the language reserved for its own grammar — you can never use one as an identifier. Nobody memorises them alphabetically; you meet them in families, and you already own the first two rows.
| FAMILY | THE KEYWORDS | WHERE YOU MEET THEM |
|---|---|---|
| Primitive types | byte short int long float double char boolean | Today — Part 4's eight boxes |
| Flow control | if else switch case default for while do break continue return | Class 4 — decisions & loops |
| Class machinery | class new this static void package import | Classes 8–9 — your first real class |
| Inheritance & contracts | extends super interface implements abstract final instanceof enum | Classes 10–12 — family trees |
| Access gates | public private protected | Class 13 — who may touch what |
| Exceptions | try catch finally throw throws assert | Unit III — when things go wrong |
| Specialist modifiers | synchronized volatile transient native strictfp | Later units — threads & files |
| Reserved but unused | goto const | Nowhere — reserved so nobody ever writes them |
And three famous impostors: true, false and null are technically literals, not keywords — values, like 840 is a value. But they are just as reserved: int true = 1; is refused all the same. If the exam asks "is true a keyword?", the full-marks answer is "a reserved literal — reserved like a keyword, classified as a value."
PART 7 · THE OTHER KIND OF BOX
Primitives hold the value. References hold the address.
Java has exactly two kinds of variable. The eight primitives keep the value inside the box. Everything else — String, Scanner, every class you'll ever write — keeps the object elsewhere and stores only its address.
int bill = 840; — open the box, the 840 is right there. Copy the variable and you copy the number itself; the two copies never affect each other.
Scanner sc = new Scanner(...) — the Scanner machine sits elsewhere in memory; sc holds a tag pointing at it. Copy sc and you copy the tag — both tags point at the same one machine.
Primitives are all-lowercase keywords: int, double, boolean. Reference types start with a capital letter because they are class names: String, Scanner. The capital is the tell.
Why should you care this early? Because Activity 3 asks you to sort six variables into these two families, because the exam asks the difference for an easy 2 marks, and because in Class 8 — when two variables point at the same ExpenseRegister and one flatmate's change shows up in the other's printout — this picture is the entire explanation. Plant it now.
PART 8 · MOVING BETWEEN BOXES
Widening flows free. Narrowing spills.
Values move between differently-sized boxes all the time. Pour a small cup into a big one and nothing is lost — Java does it silently. Pour a big cup into a small one and something may spill — Java demands your written signature: the cast.
FIRST — WHY WOULD A VALUE EVER NEED TO CHANGE BOXES? THREE REAL REASONS
Math.random() returns a double — but a dice game needs an int 1–6. Without a cast, int dice = Math.random() * 6; is a compile error. Fix: (int)(Math.random() * 6) + 1.
Trish's 5-subject total is int total = 417; — but her average is 83.4, which no int can hold. (double) total / 5 widens before dividing. The worked example below runs exactly this.
A sensor protocol or file format may demand a byte (−128…127). Your computed int level = 200; must be squeezed: byte b = (byte) level; — and the squeeze changes the number. The bit diagram below shows exactly how.
DIAGRAM 1 · WIDENING — THE VALUE 42 CLIMBS THE LADDER, NOTHING LOST, NO CAST · ONE CUP PER PRESS
Same 42 in every cup — a bigger box always has room. That's why Java never asks permission to widen. ✦
DIAGRAM 2 · NARROWING — WHERE (byte) 200 BECOMES −56, BIT BY BIT · ONE ROW PER PRESS
200 AS AN int — 32 BITS, PLENTY OF ROOM
128 + 64 + 8 = 200 — the value lives entirely in the last 8 bits… almost.
THE CAST CUTS — ONLY THE LAST 8 BITS FIT INTO A byte, THE REST ARE THROWN AWAY
Same 8 bits — but in a byte, the first bit is now the sign bit, and it landed on a 1.
THE byte RE-READS ITS 8 BITS — SIGN BIT SAYS "NEGATIVE"
1100 1000 read as a signed byte = −128 + 64 + 8 = −56. No error, no warning — the cast was your signature accepting exactly this.
200 didn't "become" −56 by magic — the top 24 bits were amputated and the sign bit flipped the meaning of what remained. ✦
FOUR MORE ONE-LINERS — SAY THE RESULT BEFORE READING THE RIGHT COLUMN
| THE LINE | KIND | WHAT ACTUALLY HAPPENS |
|---|---|---|
int i = 'A'; | widening | charint is silent: i = 65, the Unicode number under 'A'. |
double d = 7; | widening | intdouble is silent: d = 7.0. Every int fits a double exactly. |
int x = (int) 9.99; | narrowing | x = 9 — the cast truncates toward zero, it never rounds. (int) −9.99 is −9. |
int y = 3.0; | illegal | Compile error: incompatible types: possible lossy conversion from double to int — Java refuses the leftward hop without your signature. |
WHY WOULD ANYONE CAST? — FOUR REAL-LIFE MOMENTS WHERE THE CAST SAVES THE DAY
| REAL SITUATION | THE LINE YOU WRITE | WITHOUT THE CAST, WHAT GOES WRONG |
|---|---|---|
| Splitting a ₹1000 dinner bill among 3 friends | double share = (double) 1000 / 3; | int ÷ int says ₹333 — one whole rupee silently vanishes from the table. The cast gives ₹333.33… so nobody underpays. |
| Cricket strike rate — 47 runs off 38 balls | (double) runs / balls * 100 | int math reports a strike rate of 100. The real answer is 123.68 — a selector would drop the batter over a missing cast. |
| Marks percentage — 417 out of 500 | (double) marks / 500 * 100 | Worst one of all: 417 / 500 as ints is 0, so the whole thing prints 0.0%. The student "failed" because of a missing cast, not missing marks. |
| Download progress bar — 734 of 2048 bytes done | int pct = (int)(done * 100.0 / total); | Here the cast goes the OTHER way: the math is done in double (35.83…), then deliberately cut to 35 because a progress bar only shows whole percent. Casting is a choice, not an accident. |
Same tool, two jobs: cast before dividing to rescue the decimals, or cast after the maths to deliberately drop them. What matters is that it is always YOUR signed decision. ✦
WORKED EXAMPLE 3 · TRISH'S EXAM AVERAGE — WHERE THE CAST EARNS ITS KEEP
- Class
Average, saved asAverage.javainclass-03; no Scanner — values are fixed:total = 417,count = 5. - Line 8 prints
total / countas-is (int ÷ int). - Line 9 prints
(double) total / count— the cast BEFORE the division.
83 (truncated) then 83.4 (cast widened first). If both say 83, the cast is in the wrong place.C:\Users\diya\Desktop\java-practice\class-03> java Average
83 <- line 8: int ÷ int TRUNCATES
83.4 <- line 9: cast widens total first
Truncation isn't rounding — 83.999 would also become 83. The .4 wasn't lost at printing; it was never computed. ✦
Line 8 divides before anything can widen — 417/5 computes as 83 and the remainder is discarded, silently, with no error. The cast on line 9 widens total to 417.0 first, forcing a double division. Lab 0 flags this again; the exam loves asking "predict the output" on exactly this trap.
PART 9 · YOUR TURN · PREDICTION
Activity 1 — predict Rohit's mess-bill splits.
Rohit built a split calculator with everything from this hour. Below is his code and three sample runs. In your ruled notebook, predict the printed share for each run — before anything executes. Two of the three hide today's traps.
THREE RUNS — PREDICT EACH PRINTED SHARE
RUN A: bill = 840 people = 4 RUN B: bill = 1200 people = 3 RUN C: bill = 75 people = 1
AND ONE MORE — THINK, DON'T RUN
RUN D: bill = 850 people = 4
— is the flat's money safe?
RULED NOTEBOOK FIRST — FOUR PREDICTIONS, ONE REASON EACH
Write "Share = ___" for runs A, B and C, and one sentence for D naming where the missing rupees went. Only then unlock the sheet.
Predict first — a guess you committed to is worth ten you didn't.
C:\Users\diya\Desktop\java-practice\class-03> java Split (original)
Share = 212 (₹2 lost)
C:\Users\diya\Desktop\java-practice\class-03> java Split (with the cast)
Share = 212.5 (every paisa accounted)
Anyone can guess 212. The full-credit answer names the mechanism: int ÷ int truncates toward zero before anything is printed. In the exam, one sentence of mechanism turns a half-mark guess into full marks.
PART 10 · YOUR TURN · ERROR DETECTION
Activity 2 — the booking that forgot its own name.
Krish wrote a movie-seat booking prompt. It compiles, it runs — and it prints a blank name every single time. The bug is one you were warned about in Part 5. Find it, name it, fix it — notebook first.
C:\Users\diya\Desktop\java-practice\class-03> java Booking
Seats: 2
Name: <- never waits! skips straight past
2 seats for <- blank name
RULED NOTEBOOK FIRST — NAME THE BUG, WRITE THE FIX
Two sentences: (1) what is sitting in the input pipe when line 10 runs, and (2) the one line you would add or change. Hint: Part 5's warning box already told you.
Bugs you diagnose yourself never bite you twice.
C:\Users\diya\Desktop\java-practice\class-03> java Booking
Seats: 2
Name: Krish Varma
2 seats for Krish Varma
One flushing nextLine() between a number and a line. Lab 0 names this the "nextLine swallow" — you've already beaten it. ✦
PART 11 · YOUR TURN · CLASSIFICATION
Activity 3 — sort Krish's library-card variables.
Krish began a program for the flat's shared book pile. Six declarations, two families — primitive (the box holds the value itself) or reference (the box holds an address). Sort all six in your ruled notebook, and justify one of them in a full sentence.
YOUR TABLE — TWO COLUMNS, SIX NAMES
PRIMITIVE REFERENCE (value in box) (address in box) ________ ________ ________ ________ ________ ________
THEN, ONE SENTENCE
Pick ONE variable and justify its family — "because the box holds ___, not ___."
RULED NOTEBOOK FIRST — SIX NAMES, TWO COLUMNS, ONE SENTENCE
Part 2's shelf lists every primitive there is. Anything NOT on that shelf can only be one other thing.
Sort first — the shelf from Part 2 is the whole answer key.
"studentName is a reference because its box does not hold the characters K-r-i-s-h — it holds the ADDRESS of a String object on the heap that does."
The trap is joinDate — it LOOKS like a date, but Java sees only what the type says: String, so it is a reference. The type on the left of the declaration decides the family, never the meaning of the data. ✦
The eight primitives are a closed list: byte, short, int, long, float, double, char, boolean. If the type is not one of those eight words, it is a reference — String, arrays, Scanner, every class you will ever write. Two seconds, full marks.
PART 12 · MANY VALUES, ONE NAME
The array — a numbered tray of same-type boxes.
Diya has five subject marks. Five separate variables — m1, m2, m3, m4, m5 — would drown Class 4's loops before they start. One array gives her five slots under one name, numbered from zero.
BUILD-UP · THE TRAY, ONE SLOT PER PRESS — WATCH THE INDEX START AT 0
int[] marks = new int[5]; · five int boxes, one name, indexes 0–4
Five slots, last index 4. Ask for [5] and Java throws ArrayIndexOutOfBoundsException — at RUN time, loudly. ✦
int[] marks = new int[5]; — new again! An array is an object on the heap; marks is a reference tag pointing at it. All five slots start at int's default: 0.
int[] marks = {86, 74, 91, 68, 88}; — the initialiser counts the values and sizes the tray itself. Braces here are a list, not a block.
marks.length — no parentheses; it's a fixed fact, not a method. The bounds rule in one line: valid indexes run 0 to length−1.
Why start at zero? The index is an offset — "how many boxes past the start?" The first box is zero steps past the start. Every off-by-one bug you'll ever write (and Activity 6 below has one waiting) comes from forgetting this one sentence.
Integer division fails silently (wrong number, no error). Index out of bounds fails loudly (program stops with ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5). Learn to read that message now — Class 17 turns exceptions into a full chapter.
PART 13 · WORKED EXAMPLE · THE TRAY, WALKED
Diya's five marks — which subject won?
The tray holds 86, 74, 91, 68, 88. Somewhere in there is a best subject. The program below walks the tray once and keeps a running champion. One new keyword appears — for — and Class 4 owns its full story; today, read line 8 as plain English: "for each index i from 1 to the end of the tray."
C:\Users\diya\Desktop\java-practice\class-03> javac Marks.java
C:\Users\diya\Desktop\java-practice\class-03> java Marks
Best: subject 2 scored 91
Subject 2, not 3 — indexes start at 0. The champion changed hands exactly once, at i = 2, and never again. Activity 5 makes you prove that on paper. ✦
Save it — you'll trace it next. This exact loop is the exam's favourite "predict the output" body, and Activity 5 below walks it pass by pass in your notebook. If the walk feels fast today, that's fine — Class 4 slows the for keyword all the way down.
PART 14 · YOUR TURN · CLASSIFICATION
Activity 4 — IS-A, HAS-A, or neither?
Class 2 gave you the two relationship words. Today's reference types showed you what HAS-A really is under the hood — a box holding the address of another object. Six Hyderabad pairs below: in your notebook, mark each IS-A, HAS-A, or neither — and for the "neither", say why in one line.
Every Ola driver is, before anything else, one of these.
The order record carries one of these inside it, from pickup to your door.
Three wheels, one meter, and a family it clearly belongs to.
The room record keeps track of who lives in it.
Careful with this one — say the sentence out loud before you commit.
Krish's card from Activity 3 — whose name is printed on it, and why does the card need to know?
RULED NOTEBOOK FIRST — SIX VERDICTS, ONE "WHY" FOR THE ODD ONE OUT
The test sentences from Class 2 still work: IS-A must survive "a ___ is a ___"; HAS-A must survive "a ___ has a ___". If BOTH sentences feel wrong, you've found the neither.
Say each test sentence out loud first — your ear catches what your eye forgives.
HAS-A is not a metaphor anymore. In Java it is literally a reference variable inside an object:
class LibraryCard { String owner; }
That String owner box holds an address — the exact picture from Part 7. When Class 10 makes IS-A real with extends, HAS-A will already be old news to you. ✦
PART 15 · YOUR TURN · CODE TRACING
Activity 5 — trace i and max, pass by pass.
Part 13's Marks.java again — but this time you are the JVM. In your ruled notebook, draw a four-column trace table (pass · i · marks[i] · max after) and walk every pass of the loop by hand. The exam asks exactly this, worth easy full marks for a tidy table.
YOUR TRACE TABLE — FILL EVERY CELL
pass i marks[i] max after start — — 86 1 1 74 ___ 2 2 91 ___ 3 3 68 ___ 4 4 88 ___
RULED NOTEBOOK FIRST — THE FULL TABLE, THEN TWO QUESTIONS
(1) On which pass does the champion change hands? (2) Why does the loop start at i = 1 and not i = 0?
A trace you wrote yourself is the one you'll rewrite correctly in the exam hall.
(1) Pass 2 — and never again. One handover in five passes.
(2) i starts at 1 because marks[0] is ALREADY the champion — comparing it against itself on pass 0 would waste a pass and prove nothing.
Exam craft: always write the "start" row before pass 1. Most lost marks in trace questions are a missing initial state, not a wrong comparison. ✦
PART 16 · YOUR TURN · ERROR DETECTION
Activity 6 — the forecast that crashes on day five.
Trish wrote a 5-day Hyderabad temperature printer. It compiles, prints five perfect lines — then stops with a red exception. Part 12 warned you this alarm bell rings loudly. Find the bug, name the exact index that causes it, fix it — notebook first.
C:\Users\diya\Desktop\java-practice\class-03> java Forecast
Day 0: 41 C … Day 4: 43 C <- all five, perfect
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 5
RULED NOTEBOOK FIRST — THE INDEX, THE WHY, THE FIX
Three lines: (1) which value of i asks for a slot that doesn't exist, (2) the one-sentence bounds rule it broke, and (3) the fixed line 6 — written two different ways if you can.
Read the exception message like a letter — it names the index AND the length.
C:\Users\diya\Desktop\java-practice\class-03> java Forecast
Day 0: 41 C · Day 1: 42 C · Day 2: 40 C · Day 3: 39 C · Day 4: 43 C
Clean exit, no exception. Compare your two alarm bells one last time: integer division fails SILENTLY, bounds fail LOUDLY — today taught you to hear both. Next stop: operators, and the road to Lab 0. ✦
Hard-coding 5 plants the same bug again the day the array grows to 7. temps.length can never disagree with the tray it measures — that's why every loop from Class 4 onward uses it.
Seven short sheets — before the next class, thirty minutes.
Everything below extends what you built today; nothing needs a new idea. Class 4 assumes you've read the first three; Diya's marks walk (worked AND traced in class) becomes Krish's jagged cricket register on paper.
SELF-STUDY SHEET 1 OF 7 · DECLARATION vs INITIALISATION
Two steps, in slow motion — and who gets a default value.
Part 8 showed the two-step story at class speed. Here it is frozen frame by frame — plus the rule nobody tells you: local boxes get no default value; heap slots do.
- Class
Defaults, saved asDefaults.javainclass-03. - Declare
int bill;WITHOUT a value; keep the commented-out println above the assignment (uncomment it once to watch javac refuse). - Assign
bill = 840;then print it; then makenew int[3]and print slot 0 untouched.
bill = 840 then tray[0] = 0 — the 0 was never typed by you.C:\Users\diya\Desktop\java-practice\class-03> javac Defaults.java
C:\Users\diya\Desktop\java-practice\class-03> java Defaults
bill = 840
tray[0] = 0
Line 6's local box printed nothing until line 8 filled it — javac guards you. Line 10's heap slots came pre-zeroed. Two worlds, two rules. ✦
int bill; — a box is reserved and named. Type fixed forever, contents undefined. Reading it now is a compile-time error, not a runtime one.
bill = 840; — the first assignment. From this line on, reading is legal. One line can do both: int bill = 840; — that's what most of today's code did.
Locals (inside a method): none — javac refuses uninitialised reads. Array slots & fields (heap): int gets 0, double gets 0.0, boolean gets false, references get null. Fields return in Class 8.
javac answers error: variable bill might not have been initialized — before the program ever runs. That's the compiler being your safety net, the same net that caught Part 7's type errors.
SELF-STUDY SHEET 2 OF 7 · WHAT A TYPE REALLY IS
A data type = a set of permissible values + the legal operations on them.
Today you met the 8 primitives as box sizes. The exam wants the formal sentence — and once you read it, every "why won't Java let me…?" question answers itself.
A data type is a set of permissible values together with the set of legal operations on those values. Two halves, one sentence, four marks.
Set: exactly two values, true and false. Operations: logic only (&&, ||, ! — Class 4). true + true is meaningless — the operations half forbids it.
Set: whole numbers from −2,147,483,648 to 2,147,483,647 (the 4-byte range from Part 6). Operations: + − * / % and comparisons. Step outside the set and you get overflow — the wrap-around you saw today.
char's set is 0–65,535 (character codes), and its legal operations include integer arithmetic — so 'A' + 1 is 66. Not a trick: the definition, applied.
Exam-quotable, one breath: "int is not just a box size — it is the set of 32-bit whole numbers plus the arithmetic and comparison operations defined on them. A type tells the compiler what may be stored and what may be done." Write that and the marker has nothing left to deduct.
SELF-STUDY SHEET 3 OF 7 · 1D ARRAYS, EVERY FORM
One page, every way to declare a tray.
Part 12 built the tray one slot at a time. This sheet is the reference card: all three creation forms, the .length fact, and the last-slot idiom Thursday's for-loop will lean on.
- Class
ArraySyntax, saved asArraySyntax.javainclass-03. - Form 1:
new int[5]· Form 2: the marks list{86, 74, 91, 68, 88}· Form 3: declare first, fill later withnew int[]{10, 20}. - Print
b.length(no parentheses — it's a fact, not a method) andb[b.length - 1].
5 then 88 — the tray's size and its last slot.C:\Users\diya\Desktop\java-practice\class-03> javac ArraySyntax.java
C:\Users\diya\Desktop\java-practice\class-03> java ArraySyntax
5
88
b.length − 1 is the last-slot idiom — it stays correct even when the tray grows. Thursday's loop is one line away: for (int i = 0; i < b.length; i++). ✦
Sized (new int[5]), listed ({…} — only legal on the declaration line), late (new int[]{…}). All three make the same thing: a heap object with a fixed length.
Compare: sc.nextInt() does work (a method), marks.length is a fact (a fixed field). Writing length() on an array is a compile error the exam loves to plant.
for (int i = 0; i < b.length; i++) — start at 0, stop before length. The < (never <=) is exactly what Part 16's crash was about. Class 4 makes this muscle memory.
SELF-STUDY SHEET 4 OF 7 · 2D ARRAYS
A tray of trays — your timetable is already one.
Three days, four periods each: twelve room numbers. Twelve variables? Never. One grid: int[][] grid = new int[3][4]; — read the picture at home, run the loops after Class 4.
- Class
TimeTable, saved asTimeTable.javainclass-03. - Make
new int[3][4]; set Mon period 1 to room101and Wed period 4 to room204. - Nested for-loops: outer walks
grid.lengthrows, inner walksgrid[r].lengthcolumns;println()ends each day's row.
101 0 0 0 · 0 0 0 0 · 0 0 0 204 — the ten untouched slots print their default 0.C:\Users\diya\Desktop\java-practice\class-03> javac TimeTable.java
C:\Users\diya\Desktop\java-practice\class-03> java TimeTable
101 0 0 0
0 0 0 0
0 0 0 204
Ten untouched slots printed their default 0 — Sheet 1's rule at work. grid.length counts rows; grid[r].length counts that row's columns. Hold that thought for Sheet 5. ✦
grid[2][3] — row first, then column: "tray number 2, slot number 3." Both start at zero, so that's the third day's fourth period.
grid is a 3-slot tray whose slots each hold a reference to a 4-slot int tray. That's why grid[r] alone is a valid thing — it's a whole row.
A cinema hall (rows × seats), a marks register (students × subjects), a game board. Any time the data has two independent coordinates, a 2D array is the honest shape.
SELF-STUDY SHEET 5 OF 7 · JAGGED ARRAYS
Krish's cricket register — rows of different lengths.
Week 1 had 3 practice sessions, week 2 had 5, week 3 had 2. A rectangular grid would waste slots or crash. Because a 2D array is an array of arrays (Sheet 4), each row can be its own size.
C:\Users\diya\Desktop\java-practice\class-03> javac Cricket.java
C:\Users\diya\Desktop\java-practice\class-03> java Cricket
Week 1: 3 sessions
Week 2: 5 sessions
Week 3: 2 sessions
Line 6 built only the OUTER tray — new int[3][] with the second bracket empty. Lines 7–9 hung a different-sized inner tray on each slot. That's only possible because each row is its own array object. ✦
new int[3][] is legal; new int[][4] is not. Java must know how many rows exist, but each row's length can wait until you attach it.
In a jagged array there is no single "column count" — every row answers for itself. That's why Sheet 4's inner loop asked grid[r].length, not a fixed 4. Same loop, now essential.
Marks for electives (different students, different subject counts), daily orders per week, sessions per week — whenever "rows" are real-world groups of unequal size.
SELF-STUDY SHEET 6 OF 7 · ARRAY OF OBJECTS
Book[] shelf — ten tags, all pointing at nothing (yet).
Arrays don't only hold primitives. A Book[] is a tray of reference tags — and until you stamp a Book into each slot, every tag is null. Lab 1 builds exactly this shelf.
C:\Users\diya\Desktop\java-practice\class-03> javac Shelf.java
C:\Users\diya\Desktop\java-practice\class-03> java Shelf
null
Java in Depth
Line 11 printed null — the tag exists, the Book doesn't. One new Book() later, the same slot answers with a title. Two steps: build the shelf, then stamp Books into it. Lab 1, in miniature. ✦
It makes ten reference slots, each defaulting to null. The most common wrong answer in this chapter's exam question — now you'll never give it.
shelf[1].title right now throws NullPointerException — the tag points at nothing, so there is no title to read. Fill the slot first, then use it.
Lab 1's library keeps every Book in exactly such an array; Class 4's loops walk it; Class 8 gives Book a proper constructor so line 12–13 collapse into one.
SELF-STUDY SHEET 7 OF 7 · SHADOWING
Two boxes, one name — who wins?
Part 10 drew scope as nested rooms. Shadowing is the corner case: an inner room declares a name the outer room already owns. Java's answer is stricter than you'd guess — and it's a one-rule sheet.
C:\Users\diya\Desktop\java-practice\class-03> javac Shadow.java
C:\Users\diya\Desktop\java-practice\class-03> java Shadow
5
105
Line 7 legally shadows the field; line 10 would be a compile error because a local cannot shadow another local in the same method. And the outer field is still reachable by its full name — Shadow.count. ✦
A local may shadow a field (class-level box) — legal, nearest wins. A local may not re-declare a name another local already holds in an enclosing block — compile error.
When a name is legal in two rooms at once, the innermost declaration is the one every read and write touches. The outer box is untouched — hidden, not destroyed.
Class 8's constructors write this.title = title; — a parameter shadowing a field, resolved with this. This self-study sheet is the reason that line will read as obvious, not magic.
Done — all seven sheets. Thirty minutes, six runnable files, zero new machinery: every sheet reused today's boxes, tags, trays and rooms. Class 4 assumes Sheets 1–3; Sheets 4–7 turn Lab 1 from new material into revision.
PART 18 · BEFORE YOU GO
Your folder, your homework, your next hour.
Six programs today — each one a conversation, not a monologue. If your machine matches this tree, today succeeded.
HOMEWORK · DUE BEFORE CLASS 4
BillSplit.java
Rohit's Split.java, but honest: read bill and people, print the share using the double cast so no rupee ever vanishes. Test with 850 and 4 — you must see 212.5.
No code — ruled notebook only. Draw the shelf from memory: name, size, default for all eight. Check against Part 2, mark your own slips. The exam asks this cold.
Part 12 above, thirty minutes. Class 4 opens with a warm-up trace on an array walk — the 1D-array sheet is the one you cannot skip.
Homework 1 and 2 solved below — run yours first, then compare line by line.
C:\Users\diya\Desktop\java-practice\class-03> javac BillSplit.java
C:\Users\diya\Desktop\java-practice\class-03> java BillSplit
Bill: 850
People: 4
Share = 212.5
If yours printed 212, look at line 11 — the cast must land on bill BEFORE the division. Casting the whole bracket, (double)(bill / people), is too late: the rupee is already gone.
HW 2 · the eight-primitives shelf — check your notebook against this row. byte 1 B · 0 — short 2 B · 0 — int 4 B · 0 — long 8 B · 0L — float 4 B · 0.0f — double 8 B · 0.0 — char 2 B · '\u0000' — boolean JVM-dependent · false.
char defaults to '\u0000' (not a space, not 0); boolean's size is not fixed by the spec — write "JVM-dependent" in the exam; and defaults apply to fields only — a local variable has NO default, the compiler refuses to read it uninitialised.