Unit 1 home
CLASS 3 · PART B JAVA LEARNS TO LISTEN UNIT I · UI24PC320CS
CLASS 3 · P 1/13PGDN NEXT POINT · PGUP BACK

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.

THIS CLASSC3 · Scanner · 8 primitives · variables & scope · casting · arrays
NEXT CLASSC4 · Operators & control flow — the longest class in the unit
STORY SPINEThe register goes interactive — the mess-bill split calculator
TOOLINGJDK 21 LTS · Notepad++ · Command Prompt
AFTER THIS CLASS YOU CAN
  • 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.
WHERE THIS SITS
TODAY, IN ORDER
  • 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

1 BYTEbyte

−128 to 127. Tiny — a spice box. Rarely typed, often stored.

default 0

2 BYTESshort

−32,768 to 32,767. A lunchbox. Legacy files and old formats.

default 0

4 BYTESint

±2.1 billion, roughly. The everyday choice — roll numbers, headcounts, rupees.

default 0 · ★ TODAY'S WORKHORSE

8 BYTESlong

±9.2 quintillion. Aadhaar numbers, milliseconds since 1970. Literal ends in L.

default 0L

DECIMALS · TWO PRECISIONS

4 BYTESfloat

~7 digits of precision. Literal ends in f: 3.14f.

default 0.0f

8 BYTESdouble

~15 digits. The default for decimals — bills, averages, percentages. Just write 840.50.

default 0.0 · ★ DECIMAL WORKHORSE

ONE CHARACTER · ONE TRUTH

2 BYTESchar

A single character in single quotes: 'A', '₹'. Two bytes because Java speaks Unicode — Telugu included.

default '\u0000'

1 BIT*boolean

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 is NOT on the shelf.

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

KEYBOARD

Rohit types 840 and presses Enter. Raw keystrokes, nothing more.

System.in

The standard input stream — a pipe of raw characters: '8' '4' '0' ⏎. Java can't add these yet.

Scanner

The reading machine. nextInt() reads the characters and assembles a real int out of them.

int bill = 840

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. ✦

1 · Import it

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.

2 · Build it

Scanner sc = new Scanner(System.in); — stamp one Scanner object (Class 2's new!) and bolt it onto the keyboard stream.

3 · Ask it

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.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-03\Square.java
MINI PROBLEM · SQUARE.JAVA
PROBLEM
Ask the user for one whole number and answer back with its square — your first program that listens.
REQUIRE­MENTS
  • Class Square, saved as Square.java in class-03; import java.util.Scanner on line 2.
  • Prompt with print (not println) so typing happens on the same line: Enter a number:
  • Read one int with nextInt(); print Square = followed by n × n.
EXPECTED OUTPUT
user types 13 — program answers Square = 169.
Square.java — Notepad++
1// Square.java — read a number, answer with its square
2import java.util.Scanner;
3public class Square
4{
5 public static void main(String[] args)
6 {
7 Scanner sc = new Scanner(System.in);
8 System.out.print("Enter a number: ");
9 int n = sc.nextInt();
10 System.out.println("Square = " + n * n);
11 }
12}
COMMAND PROMPT — THE CONVERSATION

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 vs println — line 8

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.

The pause — line 9

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.

The + glue — line 10

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.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-03\Greet.java
MINI PROBLEM · GREET.JAVA
PROBLEM
Read a person's full name — spaces included — and greet them back. next() would stop at the first space; this program must not.
REQUIRE­MENTS
  • Class Greet, saved as Greet.java in class-03; Scanner imported.
  • Prompt Your full name: then read the WHOLE line with nextLine().
  • Print one line: Welcome, + the full name + !
EXPECTED OUTPUT
user types Diya Reddy — program answers Welcome, Diya Reddy! with the space kept (with next() it would wrongly say just Welcome, Diya!).
Greet.java — Notepad++
1// Greet.java — read a full name, greet it back
2import java.util.Scanner;
3public class Greet
4{
5 public static void main(String[] args)
6 {
7 Scanner sc = new Scanner(System.in);
8 System.out.print("Your full name: ");
9 String name = sc.nextLine(); // whole line, spaces kept
10 System.out.println("Welcome, " + name + "!");
11 }
12}
TWO RUNS — NEXT() VS NEXTLINE()

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. ✦

Trap preview — the leftover Enter.

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.

Declaration — order the box

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.

Initialisation — first fill

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).

Scope — where the name lives

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.

Same block, same name — never twice.

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.

The four hard rules

(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.

The convention everyone reads

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.

Legal ≠ good

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.

Exam sentence, ready-made: "An identifier is the name a programmer gives to a variable, class or method; it may contain letters, digits, _ and $, must not begin with a digit, must not be a keyword, and is case-sensitive." Two marks, four clauses, all four above.

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.

FAMILYTHE KEYWORDSWHERE YOU MEET THEM
Primitive typesbyte short int long float double char booleanToday — Part 4's eight boxes
Flow controlif else switch case default for while do break continue returnClass 4 — decisions & loops
Class machineryclass new this static void package importClasses 8–9 — your first real class
Inheritance & contractsextends super interface implements abstract final instanceof enumClasses 10–12 — family trees
Access gatespublic private protectedClass 13 — who may touch what
Exceptionstry catch finally throw throws assertUnit III — when things go wrong
Specialist modifierssynchronized volatile transient native strictfpLater units — threads & files
Reserved but unusedgoto constNowhere — 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."

Why you never notice this list day-to-day: Notepad++ paints keywords blue the instant you type them — the colouring you've watched since Square.java IS the reserved list announcing itself. If a name you invented turns blue, pick another name.

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.

Primitive box · value inside

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.

Reference box · address inside

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.

The naming giveaway

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

1 · The method hands you the wrong size

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.

2 · Division refuses decimals

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.

3 · Hardware wants small boxes

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

byte42 short42 int42 long42 float42.0f double42.0
WIDENING · AUTOMATIC · every rightward hop is silent: int i = b; NARROWING · every leftward hop needs your signature: byte b = (byte) i;

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

0× 24 more zeros 11001000

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

0× 24 cut off 11001000

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 LINEKINDWHAT ACTUALLY HAPPENS
int i = 'A';wideningcharint is silent: i = 65, the Unicode number under 'A'.
double d = 7;wideningintdouble is silent: d = 7.0. Every int fits a double exactly.
int x = (int) 9.99;narrowingx = 9 — the cast truncates toward zero, it never rounds. (int) −9.99 is −9.
int y = 3.0;illegalCompile 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 SITUATIONTHE LINE YOU WRITEWITHOUT THE CAST, WHAT GOES WRONG
Splitting a ₹1000 dinner bill among 3 friendsdouble 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 * 100int 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 * 100Worst 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 doneint 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

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-03\Average.java
MINI PROBLEM · AVERAGE.JAVA
PROBLEM
Trish scored 417 marks across 5 subjects. Print her average TWICE — once the broken int-division way, once correctly with a cast — and see the difference on screen.
REQUIRE­MENTS
  • Class Average, saved as Average.java in class-03; no Scanner — values are fixed: total = 417, count = 5.
  • Line 8 prints total / count as-is (int ÷ int).
  • Line 9 prints (double) total / count — the cast BEFORE the division.
EXPECTED OUTPUT
Two lines: 83 (truncated) then 83.4 (cast widened first). If both say 83, the cast is in the wrong place.
Average.java — Notepad++
1// Average.java — why 417 / 5 refuses to be 83.4
2public class Average
3{
4 public static void main(String[] args)
5 {
6 int total = 417; // five subjects, summed
7 int count = 5;
8 System.out.println(total / count); // int ÷ int
9 System.out.println((double) total / count); // cast first!
10 }
11}
THE TWO ANSWERS

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. ✦

int ÷ int is int. Always.

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.

Split.java — Rohit's calculator
1import java.util.Scanner;
2public class Split
3{
4 public static void main(String[] args)
5 {
6 Scanner sc = new Scanner(System.in);
7 int bill = sc.nextInt(); // rupees, whole
8 int people = sc.nextInt();
9 System.out.println("Share = " + bill / people);
10 }
11}

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.

SOLUTION SHEET · ONE RUN PER STEP
Split.java — all four runs traced
A// 840 / 4 -> int / int -> 210 exactly. Share = 210, clean
B// 1200 / 3 -> 400 exactly. Share = 400, clean
C// 75 / 1 -> 75. One diner pays the whole bill. Share = 75
D// 850 / 4 -> 212, NOT 212.5 - int division TRUNCATES.
// 4 × 212 = 848. TWO RUPEES VANISH — the register won't balance.
FIX System.out.println("Share = " + (double) bill / people);
RUN D · BEFORE AND AFTER THE FIX

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)

Marking yourself? The reason earns the mark, not the number.

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.

Booking.java — compiles fine, behaves wrong
1import java.util.Scanner;
2public class Booking
3{
4 public static void main(String[] args)
5 {
6 Scanner sc = new Scanner(System.in);
7 System.out.print("Seats: ");
8 int seats = sc.nextInt(); // takes the digits...
9 System.out.print("Name: ");
10 String name = sc.nextLine(); // ...reads WHAT, exactly?
11 System.out.println(seats + " seats for " + name);
12 }
13}
THE SYMPTOM

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.

SOLUTION SHEET · THE LEFTOVER ENTER
Booking.java — the fix, one thought per step
1// WHY: nextInt() took "2" but LEFT the Enter (\n) in the pipe.
2// nextLine() then read that leftover empty line — instantly.
8 int seats = sc.nextInt();
+ sc.nextLine(); // FLUSH the leftover Enter
10 String name = sc.nextLine(); // now reads the REAL line
AFTER THE FIX

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.

LibraryCard.java — six boxes, two families
1public class LibraryCard
2{
3 public static void main(String[] args)
4 {
5 int cardNumber = 4407;
6 String studentName = "Krish Varma";
7 double finePending = 12.50;
8 boolean isActive = true;
9 String joinDate = "2025-08-04";
10 int booksIssued = 3;
11 }
12}

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.

SOLUTION SHEET · FOUR PRIMITIVES, TWO REFERENCES
LibraryCard.java — each box, called
5// cardNumber -> int -> PRIMITIVE - the box holds 4407 itself
6// studentName -> String -> REFERENCE - the box holds an ADDRESS to the text
7// finePending -> double -> PRIMITIVE - 12.50 sits in the box
8// isActive -> boolean -> PRIMITIVE - true sits in the box
9// joinDate -> String -> REFERENCE - a date WRITTEN AS TEXT is still a String
10// booksIssued -> int -> PRIMITIVE — 3 sits in the box
THE ONE-SENTENCE JUSTIFICATION

"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. ✦

Exam shortcut — the shelf test.

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

marks[0]86 marks[1]74 marks[2]91 marks[3]68 marks[4]88 marks[5]✗ CRASH — no such slot

Five slots, last index 4. Ask for [5] and Java throws ArrayIndexOutOfBoundsException — at RUN time, loudly. ✦

Declare & create

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.

Or fill it at birth

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.

Ask its length

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.

Two traps, two different alarm bells.

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."

Marks.java — one walk, one champion
1public class Marks
2{
3 public static void main(String[] args)
4 {
5 int[] marks = {86, 74, 91, 68, 88};
6 int max = marks[0]; // first mark starts as champion
7 int best = 0; // its seat number
8 for (int i = 1; i < marks.length; i++)
9 {
10 if (marks[i] > max)
11 {
12 max = marks[i]; // new champion
13 best = i;
14 }
15 }
16 System.out.println("Best: subject " + best + " scored " + max);
17 }
18}
COMPILE · RUN

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.

1 · Ola driver … person

Every Ola driver is, before anything else, one of these.

2 · Swiggy order … delivery partner

The order record carries one of these inside it, from pickup to your door.

3 · Auto-rickshaw … vehicle

Three wheels, one meter, and a family it clearly belongs to.

4 · Hostel room … roommate

The room record keeps track of who lives in it.

5 · Charminar … Hyderabad

Careful with this one — say the sentence out loud before you commit.

6 · Library card … student

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.

SOLUTION SHEET · TWO IS-A · THREE HAS-A · ONE NEITHER
Six verdicts — each with its test sentence
1// Ola driver / person -> IS-A — "a driver IS a person" ✓ inheritance-shaped
2// Swiggy order / partner -> HAS-A — the Order object holds a partner REFERENCE
3// Auto-rickshaw / vehicle -> IS-A — "an auto IS a vehicle" ✓
4// Hostel room / roommate -> HAS-A — the Room object holds occupant references
5// Charminar / Hyderabad -> NEITHER — "Charminar IS a Hyderabad"? no.
6// "Charminar HAS a Hyderabad"? no. LOCATED-IN is not a type relationship.
7// Library card / student -> HAS-A — the card object holds its OWNER's reference
WHY THIS LANDS IN TODAY'S CLASS

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.

Marks.java — the loop, isolated
5 int[] marks = {86, 74, 91, 68, 88};
6 int max = marks[0];
7 int best = 0;
8 for (int i = 1; i < marks.length; i++)
10 if (marks[i] > max) { max = marks[i]; best = i; }

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.

SOLUTION SHEET · ONE PASS PER STEP
The trace, pass by pass
st// start : max = marks[0] = 86, best = 0 — champion by default, unbeaten so far
p1// i = 1 : marks[1] = 74 -> 74 > 86? NO -> max stays 86
p2// i = 2 : marks[2] = 91 -> 91 > 86? YES -> max = 91, best = 2 <- the ONLY handover
p3// i = 3 : marks[3] = 68 -> 68 > 91? NO -> max stays 91
p4// i = 4 : marks[4] = 88 -> 88 > 91? NO -> max stays 91
end// i = 5 : 5 < 5 fails -> loop exits -> prints "Best: subject 2 scored 91"
THE TWO QUESTIONS, ANSWERED

(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.

Forecast.java — compiles fine, stops at runtime
1public class Forecast
2{
3 public static void main(String[] args)
4 {
5 int[] temps = {41, 42, 40, 39, 43}; // 5 days of May heat
6 for (int i = 0; i <= 5; i++) // hmm — count the slots again
7 {
8 System.out.println("Day " + i + ": " + temps[i] + " C");
9 }
10 }
11}
THE SYMPTOM — FIVE GOOD LINES, THEN FIRE

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.

SOLUTION SHEET · ONE CHARACTER, ONE CRASH
Forecast.java — the fix, one thought per step
1// WHY: valid indexes run 0 to length-1 -> 0,1,2,3,4. Five slots, last index 4.
2// i <= 5 lets i reach 5 -> temps[5] -> no such slot -> LOUD crash at RUN time.
6 for (int i = 0; i < 5; i++) // fix 1: strict <
6 for (int i = 0; i < temps.length; i++) // fix 2: BETTER — survives resizing
AFTER THE FIX

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. ✦

Prefer fix 2 in every program you ever write.

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.

SELF-STUDY · READ BEFORE CLASS 4

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.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-03\Defaults.java
MINI PROBLEM · DEFAULTS.JAVA
PROBLEM
Prove the two-worlds rule on your own machine: a local variable has NO default value, but heap array slots come pre-zeroed.
REQUIRE­MENTS
  • Class Defaults, saved as Defaults.java in class-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 make new int[3] and print slot 0 untouched.
EXPECTED OUTPUT
Two lines: bill = 840 then tray[0] = 0 — the 0 was never typed by you.
Defaults.java — Notepad++
1// Defaults.java — declaration first, value later
2public class Defaults
3{
4 public static void main(String[] args)
5 {
6 int bill; // DECLARED — the box exists, empty
7 // System.out.println(bill); <- javac refuses: bill has no value yet
8 bill = 840; // INITIALISED — first value goes in
9 System.out.println("bill = " + bill);
10 int[] tray = new int[3]; // heap slots DO get defaults
11 System.out.println("tray[0] = " + tray[0]);
12 }
13}
COMMAND PROMPT

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. ✦

Declaration

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.

Initialisation

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.

Who gets a default?

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.

Try it at home: uncomment line 7.

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.

The definition — memorise it

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.

boolean, read this way

Set: exactly two values, true and false. Operations: logic only (&&, ||, ! — Class 4). true + true is meaningless — the operations half forbids it.

int, read this way

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.

Why char arithmetic works

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.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-03\ArraySyntax.java
MINI PROBLEM · ARRAYSYNTAX.JAVA
PROBLEM
Put all three 1D-array creation forms in ONE runnable file, then read two facts back out of the marks tray: its length and its last slot.
REQUIRE­MENTS
  • Class ArraySyntax, saved as ArraySyntax.java in class-03.
  • Form 1: new int[5] · Form 2: the marks list {86, 74, 91, 68, 88} · Form 3: declare first, fill later with new int[]{10, 20}.
  • Print b.length (no parentheses — it's a fact, not a method) and b[b.length - 1].
EXPECTED OUTPUT
Two lines: 5 then 88 — the tray's size and its last slot.
ArraySyntax.java — Notepad++
1// ArraySyntax.java — every 1D form on one page
2public class ArraySyntax
3{
4 public static void main(String[] args)
5 {
6 int[] a = new int[5]; // form 1 — sized, all slots 0
7 int[] b = {86, 74, 91, 68, 88}; // form 2 — list sizes itself
8 int[] c; // declare now…
9 c = new int[]{10, 20}; // …fill later: form 3 needs new int[]
10 a[0] = 42; // write one slot
11 System.out.println(b.length); // a fact, not a method — no ()
12 System.out.println(b[b.length - 1]); // the last slot, always
13 }
14}
COMMAND PROMPT

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++). ✦

Three forms, one rule

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.

.length has no ( )

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.

The walk pattern — preview

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.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-03\TimeTable.java
MINI PROBLEM · TIMETABLE.JAVA
PROBLEM
Model 3 days × 4 periods of room numbers as ONE 2D grid (never twelve variables), fill two slots, and print the whole grid row by row.
REQUIRE­MENTS
  • Class TimeTable, saved as TimeTable.java in class-03.
  • Make new int[3][4]; set Mon period 1 to room 101 and Wed period 4 to room 204.
  • Nested for-loops: outer walks grid.length rows, inner walks grid[r].length columns; println() ends each day's row.
EXPECTED OUTPUT
Three rows: 101 0 0 0 · 0 0 0 0 · 0 0 0 204 — the ten untouched slots print their default 0.
TimeTable.java — Notepad++
1// TimeTable.java — 3 days × 4 periods, one grid
2public class TimeTable
3{
4 public static void main(String[] args)
5 {
6 int[][] grid = new int[3][4]; // 3 rows × 4 columns, all 0
7 grid[0][0] = 101; // Mon, period 1 -> room 101
8 grid[2][3] = 204; // Wed, period 4 -> room 204
9 for (int r = 0; r < grid.length; r++) // rows
10 {
11 for (int c = 0; c < grid[r].length; c++) // that row's columns
12 {
13 System.out.print(grid[r][c] + " ");
14 }
15 System.out.println(); // end of one day's row
16 }
17 }
18}
COMMAND PROMPT

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. ✦

Read [r][c] left to right

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.

It's really an array of arrays

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.

Where you'll meet them

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.

Cricket.java — Notepad++
1// Cricket.java — runs scored per session, per week
2public class Cricket
3{
4 public static void main(String[] args)
5 {
6 int[][] runs = new int[3][]; // 3 weeks — row sizes left OPEN
7 runs[0] = new int[]{34, 12, 48}; // week 1 — 3 sessions
8 runs[1] = new int[]{7, 22, 51, 0, 19}; // week 2 — 5 sessions
9 runs[2] = new int[]{63, 15}; // week 3 — 2 sessions
10 for (int w = 0; w < runs.length; w++)
11 {
12 System.out.println("Week " + (w + 1) + ": " + runs[w].length + " sessions");
13 }
14 }
15}
COMMAND PROMPT

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. ✦

The empty second bracket

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.

Why runs[w].length matters

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.

When to reach for it

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.

Shelf.java — Notepad++
1// Shelf.java — a tray of Book references
2class Book
3{
4 String title; // a field — default null (Sheet 1!)
5}
6public class Shelf
7{
8 public static void main(String[] args)
9 {
10 Book[] shelf = new Book[10]; // ten TAGS — zero Books so far
11 System.out.println(shelf[0]); // what's in an unfilled slot?
12 shelf[0] = new Book(); // NOW one real Book exists
13 shelf[0].title = "Java in Depth";
14 System.out.println(shelf[0].title);
15 }
16}
COMMAND PROMPT

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. ✦

new Book[10] makes no Books

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.

Touch a null tag = crash

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.

Where this is heading

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.

Shadow.java — Notepad++
1// Shadow.java — same name, nested rooms
2public class Shadow
3{
4 static int count = 100; // class-level box (a field)
5 public static void main(String[] args)
6 {
7 int count = 5; // LEGAL — shadows the field
8 System.out.println(count); // nearest box wins
9 {
10 // int count = 9; <- ILLEGAL — javac: count is already defined
11 System.out.println(count + Shadow.count); // 5 + 100
12 }
13 }
14}
COMMAND PROMPT

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. ✦

The one rule

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.

Nearest box wins

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.

Why care now?

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.

YOUR FOLDER AFTER THIS CLASS — CHECK BEFORE YOU LEAVE
Desktop\java-practice\class-03\
Square.java <- worked ex. 1 · reads, squares, answers
Square.class <- javac made it
Greet.java <- worked ex. 2 · nextLine keeps the surname
Greet.class
Booking.java <- activity 2 · with YOUR flush fix in it
Booking.class <- proof the fix compiled
Average.java <- worked ex. 3 · the cast that saves paise
Average.class
Marks.java <- worked ex. 4 · the tray, walked once
Marks.class
Forecast.java <- activity 6 · with YOUR bounds fix in it
Forecast.class <- proof the fix compiled

HOMEWORK · DUE BEFORE CLASS 4

1 Write & run 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.

2 Paper shelf: the eight primitives

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.

3 Read the seven self-study sheets

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.

HOMEWORK SOLUTIONS · HW 1 CODE + HW 2 SHELF
BillSplit.java — the honest split, no vanishing rupee
1import java.util.Scanner;
2public class BillSplit
3{
4 public static void main(String[] args)
5 {
6 Scanner sc = new Scanner(System.in);
7 System.out.print("Bill: ");
8 int bill = sc.nextInt();
9 System.out.print("People: ");
10 int people = sc.nextInt();
11 double share = (double) bill / people;
12 System.out.println("Share = " + share);
13 }
14}
THE 850 ÷ 4 TEST

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.

The three slips almost everyone makes on the shelf.

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.