Unit 1 home
CLASS 4 · PART B EVERY OPERATOR YOU NEED UNIT I · UI24PC320CS
CLASS 4 · P 1/21PGDN NEXT POINT · PGUP BACK

UI24PC320CS · OOP THROUGH JAVA · UNIT I · PART B · LONGEST CLASS IN THE UNIT

Every operator you need —
plus one C doesn't have.

Class 3 gave your programs memory: boxes, tags, trays. Today those values start working — arithmetic, comparison, logic, bits, shifts, and the full branch-and-loop toolkit. By the last press, everything Lab 0 asks of you has been taught.

TODAY'S SPAN6 operator families · switch · do-while · break & continue
JAVA-ONLY STAR>>> unsigned right shift — C and C++ don't have it
ACTIVITIES5 locked activities — notebook first, always
FEEDSLAB 0 — every mechanic it needs ends today

BY THE END OF TODAY YOU CAN

  • predictthe printed result of any expression mixing arithmetic, comparison and logic — including the ones that short-circuit
  • tracea value through & | ^ ~ << >> >>> at the bit level, lane by lane
  • classifyany operator into its family and rank it on the precedence ladder
  • debuga fall-through switch and a do-while loop that never exits
  • answer"why does Java have THREE shift operators?" — in two exam-ready sentences

WHERE THIS SITS

TODAY'S ROAD · 21 STOPS

  • Arithmetic · relational · logical · assignment — the everyday fourSHEETS 1–3
  • Two worked examples — leap year & an Ola-style fare meterTYPE ALONG
  • Bitwise & | ^ ~ and the three shifts>>> JAVA-ONLY
  • The precedence ladder — and the exam trap x + 1 << 2EXAM CORE
  • switch — fall-through, break, and Diya's mess-menu lookup+ WORKED EX.
  • do-while — the UPI PIN loop that must run at least onceRUNS ≥ 1
  • break & continue — plus labelled break, the bus-seat searchJAVA-SPECIFIC

CLASS 04 OF 60 · 23 CORE-TAUGHT PAGES + 7 SELF-STUDY SHEETS (IN FULL, BELOW) · ZERO ASSETS TO DOWNLOAD · FEEDS LAB 0

SELF-STUDY · SHEET 1 OF 7 · READ BEFORE THIS CLASS

Arithmetic — the everyday five, plus the step twins.

+ − * / % you have used since school — but two of them behave differently inside an int box, and ++/-- hide a before/after trap the exam plants every year. Class 3's mess-bill split already showed you the wound; this sheet names the blade.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-04\Arith.java
MINI PROBLEM · ARITH.JAVA
PROBLEM
A semester mess fee of ₹4750 is split over 6 months — show how / truncates, % keeps the leftover, and one 6.0 rescues the paise. Then let seat++ vs ++seat show their before/after difference.
REQUIRE­MENTS
  • Class Arith, saved as Arith.java in class-04; start with int fee = 4750, months = 6;
  • Print fee / months, then fee % months, then fee / 6.0 — three separate lines.
  • Declare int seat = 41; then print seat++ and ++seat on their own lines.
EXPECTED OUTPUT
five lines: 791 · 4 · 791.6666666666666 · 41 · 43.
Arith.java — Notepad++
1// Arith.java — five operators, two traps
2public class Arith
3{
4 public static void main(String[] args)
5 {
6 int fee = 4750, months = 6; // hostel mess fee, one semester
7 System.out.println(fee / months); // int ÷ int — TRUNCATES
8 System.out.println(fee % months); // % = what's LEFT OVER
9 System.out.println(fee / 6.0); // one double in the mix -> real division
10 int seat = 41;
11 System.out.println(seat++); // POST: use 41 first, THEN step to 42
12 System.out.println(++seat); // PRE: step to 43 FIRST, then use it
13 }
14}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> javac Arith.java

C:\Users\diya\Desktop\java-practice\class-04> java Arith

791

4

791.6666666666666

41

43

Line 7 quietly threw ₹0.67 away every month; line 9 got it back with one 6.0. And seat printed 41 then 43 — the step twins differ only in when they step. ✦

int ÷ int truncates

Not rounds — truncates toward zero, before anything is printed. 4750/6 is 791, full stop. One double anywhere in the expression (6.0, a cast) upgrades the whole division.

% is the leftover

fee % months answers "after equal shares, what remains?" — ₹4 here. You'll use it for even/odd (n % 2), last digits (n % 10) and clock arithmetic all semester.

seat++ vs ++seat

Alone on a line, identical. Inside a bigger expression, post uses the old value, pre uses the new one. If a trace question shows a[i++], read it as: use i, then step.

The exam's favourite one-liner: System.out.println(5 / 2 + 5 % 2);

Trace it in your ruled notebook right now: 5/2 is 2 (truncated), 5%2 is 1, sum 3. If you wrote 3.5 anywhere in your working, re-read the first idea card.

SELF-STUDY · SHEET 2 OF 7

Questions and glue — relational asks, logical combines.

Six comparison operators each produce exactly one boolean. Three logical operators glue those booleans into real-world rules. And two of them practise short-circuit evaluation — Java stops reading the moment the answer is already decided.

ABA && BA || BSHORT-CIRCUIT?
truetruetruetrue
falseanythingfalseB decides&& never reads B
trueanythingB decidestrue|| never reads B
! flips one boolean: !true gives false. That's the whole operator.
SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-04\Guard.java
MINI PROBLEM · GUARD.JAVA
PROBLEM
The semester just started: classesHeld = 0. Both attendance checks divide by that zero on paper — prove that short-circuit && and || stop reading before the division ever runs.
REQUIRE­MENTS
  • Class Guard, saved as Guard.java in class-04; start with int classesHeld = 0, attended = 0;
  • shortAtt: guard classesHeld > 0 on the LEFT of &&, the percentage division on the right.
  • canSit: a true fact (82 >= 35) on the LEFT of ||, a division by zero on the right.
  • Print both booleans with labels — the program must NOT crash.
EXPECTED OUTPUT
attendance short? false then can sit exam? true — no exception, ever.
Guard.java — Notepad++
1// Guard.java — the left side saves the right side's life
2public class Guard
3{
4 public static void main(String[] args)
5 {
6 int classesHeld = 0, attended = 0; // semester just started
7 boolean shortAtt = classesHeld > 0 && attended * 100 / classesHeld < 75;
8 System.out.println("attendance short? " + shortAtt);
9 boolean canSit = 82 >= 35 || attended / classesHeld > 0; // ÷0 never runs!
10 System.out.println("can sit exam? " + canSit);
11 }
12}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> javac Guard.java

C:\Users\diya\Desktop\java-practice\class-04> java Guard

attendance short? false

can sit exam? true

Both lines divide by zero on paper — neither crashes. Line 7's left side was false, so && stopped; line 9's left side was true, so || stopped. That's short-circuit: the guard runs first. ✦

Relational: always one boolean out

== != < > <= >= — every comparison answers one yes/no. Careful: == compares, = assigns. Writing if (x = 5) is a compile error in Java — the compiler catches C's classic bug.

Guard idiom — memorise the shape

denominator > 0 && total / denominator — the check on the left protects the arithmetic on the right. Every safe division you write this semester uses this exact shape.

Exam sentence, ready to quote

"&& and || are short-circuit operators: the right operand is evaluated only if the left operand has not already decided the result." Two marks, one sentence.

SELF-STUDY · SHEET 3 OF 7

One box, updated in place — = and its five shortcuts.

= you met in Class 3: put a value in the box. The compound five — += −= *= /= %= — read the box, do the arithmetic, and put the result back in the same box. One line instead of two, plus one hidden favour the long form doesn't do.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-04\TopUp.java
MINI PROBLEM · TOPUP.JAVA
PROBLEM
A phone balance of ₹150 gets one recharge and two purchases — track it in ONE variable using compound assignment, then show the hidden cast that lets b += 1 compile where b = b + 1 refuses.
REQUIRE­MENTS
  • Class TopUp, saved as TopUp.java in class-04; start with int balance = 150;
  • Apply += 500 (recharge), -= 265 (data pack), -= 80 (caller tune) — no second variable.
  • Print left: + balance; then declare byte b = 10; and print it after b += 1;
EXPECTED OUTPUT
left: 305 then 11.
TopUp.java — Notepad++
1// TopUp.java — a phone recharge, spent in place
2public class TopUp
3{
4 public static void main(String[] args)
5 {
6 int balance = 150;
7 balance += 500; // recharge -> read 150, add, store 650
8 balance -= 265; // data pack -> 385
9 balance -= 80; // caller tune -> 305
10 System.out.println("left: " + balance);
11 byte b = 10;
12 // b = b + 1; <- ERROR: b + 1 is an int, too big a bottle for a byte box
13 b += 1; // LEGAL — compound quietly casts back to byte
14 System.out.println(b);
15 }
16}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> javac TopUp.java

C:\Users\diya\Desktop\java-practice\class-04> java TopUp

left: 305

11

One box, three updates, no second variable anywhere. And line 13 compiled where line 12 refused — compound assignment carries a built-in cast. ✦

Read, compute, store back

balance += 500 is exactly balance = balance + 500 — same box on both sides. The right side is computed with the old value; only then is the box overwritten.

The hidden cast

b += 1 really means b = (byte)(b + 1). The compound form inserts the cast for you; the long form makes you write it. A one-mark "why does this compile?" regular.

Why this matters today

The fare-meter worked example below leans on += three times, and every loop counter you'll ever write is a compound update. This is the most-typed operator family of the course.

PART 5 · WORKED EXAMPLE 1 · TYPE ALONG

The leap-year rule — three operators, one famous condition.

Every calendar app on your phone runs this exact test. The rule in words: divisible by 4 and not by 100 — or divisible by 400. Watch relational, logical and % click together into one boolean.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-04\LeapYear.java
MINI PROBLEM · LEAPYEAR.JAVA
PROBLEM
Read a year and answer whether it is a leap year — the real calendar rule: divisible by 4 and not by 100, or divisible by 400. Relational, logical and % in one boolean line.
REQUIRE­MENTS
  • Class LeapYear, saved as LeapYear.java in class-04; import java.util.Scanner.
  • Read one int with nextInt(); compute (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 into one boolean.
  • Print the year, the text leap? , and the boolean on one line.
EXPECTED OUTPUT
three runs: typing 2024 prints 2024 leap? true · 1900 prints 1900 leap? false · 2000 prints 2000 leap? true.
LeapYear.java — Notepad++
1import java.util.Scanner;
2public class LeapYear
3{
4 public static void main(String[] args)
5 {
6 Scanner sc = new Scanner(System.in);
7 int y = sc.nextInt();
8 boolean leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
9 System.out.println(y + " leap? " + leap);
10 }
11}
THREE RUNS — WATCH 1900

C:\Users\diya\Desktop\java-practice\class-04> javac LeapYear.java

C:\Users\diya\Desktop\java-practice\class-04> java LeapYear ⏎ 2024

2024 leap? true

C:\Users\diya\Desktop\java-practice\class-04> java LeapYear ⏎ 1900

1900 leap? false

C:\Users\diya\Desktop\java-practice\class-04> java LeapYear ⏎ 2000

2000 leap? true

1900 divides by 4 — and still fails, because % 100 != 0 vetoes it. 2000 gets rescued by the || y % 400 clause. One line of booleans encodes 400 years of calendar politics. ✦

Trace 1900 aloud, the way the JVM does: 1900 % 4 == 0 is true, keep reading. 1900 % 100 != 0 is false — the && group collapses to false. Last hope: 1900 % 400 == 0 — 300 remains, so false. false || false lands on false. Say a trace like that in the exam hall (on paper) and the marker follows every step with you.

The brackets around the && group are load-bearing.

They aren't — && already binds tighter than ||, so the line works bracket-free. But write them anyway: the reader shouldn't need the precedence ladder (Part 10) to see your intent. Brackets are free; confusion is not.

PART 6 · WORKED EXAMPLE 2 · TYPE ALONG

The fare meter — += earning its keep, leg by leg.

Rohit books a cab home in three hops: hostel to metro, metro to market, market to gate. The meter starts at the base fare and accumulates — exactly what compound assignment was born for. One variable, growing in place.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-04\FareMeter.java
MINI PROBLEM · FAREMETER.JAVA
PROBLEM
Rohit's cab ride home has three legs. Start the meter at the base fare and accumulate each leg's cost into the SAME variable with += — the accumulator pattern, no fare1/fare2/fare3 clutter.
REQUIRE­MENTS
  • Class FareMeter, saved as FareMeter.java in class-04; import java.util.Scanner.
  • Start with double fare = 50.0; (base) and double perKm = 12.0;
  • Read three leg distances with nextDouble(); fold each in with fare += perKm * …
  • Print Total = Rs. + fare.
EXPECTED OUTPUT
user types 3.5, 2.0, 6.5 — the meter grows 50, then 92, then 116, and prints Total = Rs.194.0.
FareMeter.java — Notepad++
1import java.util.Scanner;
2public class FareMeter
3{
4 public static void main(String[] args)
5 {
6 Scanner sc = new Scanner(System.in);
7 double fare = 50.0; // base fare — meter starts here
8 double perKm = 12.0;
9 fare += perKm * sc.nextDouble(); // leg 1 - hostel to metro
10 fare += perKm * sc.nextDouble(); // leg 2 - metro to market
11 fare += perKm * sc.nextDouble(); // leg 3 - market to gate
12 System.out.println("Total = Rs." + fare);
13 }
14}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> javac FareMeter.java

C:\Users\diya\Desktop\java-practice\class-04> java FareMeter

3.5 2.0 6.5

Total = Rs.194.0

Trace the box: 50, +42 makes 92, +24 makes 116, +78 makes 194. Same box every time, no fare1/fare2/fare3 clutter. That's the accumulator pattern — Lab 0's pass-counter is this exact shape. ✦

The accumulator pattern

Start with a seed value, fold each new piece in with +=. Totals, counters, running averages — half the programs in this course are this pattern wearing different clothes.

Precedence, quietly at work

Line 9 computes perKm * next first, then += folds it in — because * outranks assignment. You've been trusting the ladder all along; Part 10 finally shows it to you.

Why double, not int?

Kilometres come in halves (3.5 km) and rupees in paise. Class 3's rule: decimals ride in double boxes. An int meter would silently amputate every half-kilometre.

SELF-STUDY · SHEET 4 OF 7

Bitwise — the same logic, one bit at a time.

Class 3 told you an int is 32 tiny switches. Bitwise operators flip and compare those switches directly&, |, ^, ~ are AND, OR, XOR, NOT applied to every bit-pair at once. Watch 12 and 10 meet, lane by lane.

bit abit ba & ba | ba ^ b
00000
01011
10011
11110

BUILD-UP · 12 & 10, ONE LANE PER PRESS — ONLY DOUBLE-1 SURVIVES

1
1
0
0

a = 12, binary 1100

1
0
1
0

b = 10 is 1010

1
0
0
0

a & b gives 1000 = 8 — only the leftmost lane had 1 AND 1

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-04\Bits.java
MINI PROBLEM · BITS.JAVA
PROBLEM
Take the two numbers from the lane sim — 12 (1100) and 10 (1010) — and run all four bitwise operators on them, so the sim's lane-by-lane answers appear on a real terminal.
REQUIRE­MENTS
  • Class Bits, saved as Bits.java in class-04; declare int a = 12, b = 10;
  • Print a & b, a | b, a ^ b, and ~a — four lines, same two numbers.
EXPECTED OUTPUT
four lines: 8 · 14 · 6 · -13 (flipping all 32 bits of n gives −(n+1)).
Bits.java — Notepad++
1// Bits.java — four operators, same two numbers
2public class Bits
3{
4 public static void main(String[] args)
5 {
6 int a = 12, b = 10; // 1100 and 1010
7 System.out.println(a & b); // 1000 -> 8 (both must be 1)
8 System.out.println(a | b); // 1110 -> 14 (either is enough)
9 System.out.println(a ^ b); // 0110 -> 6 (different = 1)
10 System.out.println(~a); // flip all 32 -> -13
11 }
12}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> javac Bits.java

C:\Users\diya\Desktop\java-practice\class-04> java Bits

8

14

6

-13

~12 = −13 surprises everyone once: flipping all 32 bits of n always gives −(n+1) in two's complement. Verify it with ~0 = −1 — every bit on is minus one. ✦

& vs && — cousins, not twins

& works on bits of numbers, && on booleans — and only && short-circuits. Mixing them up in a condition compiles sometimes and burns you always.

Where you'll actually use this

Permission flags: read=4, write=2, execute=1. perm & 2 asks "is write on?", perm | 1 switches execute on. Class 31 revisits this as the bitmask pattern for PYQ P1·Q13b.

^ — the odd one out

XOR is 1 only when the bits differ. Its party trick: x ^ k ^ k == x — apply the same key twice and the original returns. That's toy encryption in one operator.

PART 8 · THE SHIFT FAMILY

Sliding the whole lane — why Java has three shift operators.

A shift moves every bit left or right by n lanes. Left is easy — one operator. Right forces a question C never answered cleanly: what fills the empty lanes on the left? Java's answer: you choose. Copy the sign (>>) or pour in zeros (>>>). That choice is why there are three.

FIRST, A TRICK YOU LEARNT IN PRIMARY SCHOOL — SHIFTING IS THE SAME TRICK, IN BASE 2

BASE 10 · THE HABIT YOU ALREADY HAVE

72 append a 0 720

720 append a 0 7200

Writing one extra 0 on the right multiplies any decimal number by 10 — you never "calculate" 72 × 10, you just slide the digits left and drop a zero in. Two zeros = ×100.

7200 chop last digit 720

And removing the last digit divides by 10 (the chopped digit is simply thrown away — 725 becomes 72, the 5 is gone).

BASE 2 · THE EXACT SAME TRICK = SHIFT

1100 append a 0 11000

In binary each column is worth ×2, not ×10 — so appending one 0 on the right multiplies by 2. That IS x << 1. Append two zeros = x << 2 = ×4.

11000 chop last bit 1100

Removing the last bit divides by 2 (floor) — that IS x >> 1. The chopped bit is thrown away forever, exactly like the 5 in 725 ÷ 10.

So "shift" is not a new idea at all. Left shift by n = write n zeros on the right (×2ⁿ). Right shift by n = erase the last n bits (÷2ⁿ, remainders discarded). Everything below is just watching this trick happen lane by lane.

HOW A LEFT SHIFT ACTUALLY MOVES · 12 << 2, ONE SLIDE PER PRESS — EVERY BIT WALKS ONE LANE LEFT, A FRESH 0 ENTERS ON THE RIGHT

0
0
1
1
0
0
START · 001100 = 12
0
1
1
0
0
0
SLIDE 1 · 011000 = 24 — one new 0 in, value ×2
1
1
0
0
0
0
SLIDE 2 · 110000 = 48 — TWO added zeros, value ×4

12 << 2 = 48. Count the orange cells: shifting left by 2 literally means adding 2 zeros at the right end — and 12 with two zeros appended in base 2 is 12 × 2² = 48. The trick and the machine agree.

HOW A RIGHT SHIFT ACTUALLY MOVES · 40 >> 2, ONE SLIDE PER PRESS — EVERY BIT WALKS RIGHT, THE LAST BIT FALLS OFF THE EDGE

1
0
1
0
0
0
START · 101000 = 40
0
1
0
1
0
0
FELL OFF
0
SLIDE 1 · 010100 = 20 — last bit removed, value ÷2
0
0
1
0
1
0
FELL OFF
0
0
SLIDE 2 · 001010 = 10 — two bits removed, value ÷4

40 >> 2 = 10. Right shift is the mirror move: the rightmost bits are removed and thrown away (÷2 per slide, remainders lost forever) — and something must ENTER the empty left lanes. For a positive number, plain zeros. For a negative one… that's exactly the question the next two operators answer.

Say it in one breath before moving on.

Left shift = zeros ADDED at the right, everything slides left, ×2 per lane. Right shift = bits REMOVED at the right, everything slides right, ÷2 per lane — and the left edge needs a filler, which is where >> and >>> part ways.

QUICK CHECK · 5 << 1, ONE PRESS PER STAGE — WATCH THE VALUE DOUBLE

0
1
0
1

5 is 0101

1
0
1
0

5 << 1 gives 1010 = 10 — everyone slides left, a fresh 0 fills the right. One lane left = ×2.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-04\Shifts.java
MINI PROBLEM · SHIFTS.JAVA
PROBLEM
Prove the primary-school trick on a real terminal: left shift = append zeros (×2 per lane), signed right shift = chop bits (÷2 per lane, sign kept) — including one negative number that must STAY negative.
REQUIRE­MENTS
  • Class Shifts, saved as Shifts.java in class-04 — no variables needed, four println lines.
  • Print 5 << 1, 5 << 3, 40 >> 2, then -40 >> 2.
EXPECTED OUTPUT
four lines: 10 · 40 · 10 · -10 — the sign bit was copied in, so negative in, negative out.
Shifts.java — Notepad++
1// Shifts.java — left doubles, signed right halves
2public class Shifts
3{
4 public static void main(String[] args)
5 {
6 System.out.println(5 << 1); // ×2 -> 10
7 System.out.println(5 << 3); // ×2³ -> 40
8 System.out.println(40 >> 2); // ÷2² -> 10
9 System.out.println(-40 >> 2); // sign copied in -> stays negative
10 }
11}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> javac Shifts.java

C:\Users\diya\Desktop\java-practice\class-04> java Shifts

10

40

10

-10

−40 >> 2 gave −10, not some garbage giant — because >> copies the sign bit into every vacated lane. Negative in, negative out. That's "arithmetic" right shift. ✦

<< n = × 2ⁿ

Each left slide doubles. 5 << 3 is 5 × 8 = 40. Zeros always fill from the right — there's no choice to make, which is why left shift needs only one operator.

>> n = ÷ 2ⁿ, sign kept

The leftmost bit is the sign bit (Class 3's two's complement). >> clones it into the vacated lanes, so negatives stay negative and the ÷2 arithmetic stays honest.

The open question

What if you don't want the sign copied — you just want raw bits slid right, zeros poured in? C shrugs (implementation-defined). Java gave it its own operator. Next part.

SHIFT DRILL · SIX ROUNDS — SHOUT THE ANSWER BEFORE THE STAMP LANDS · QUESTION ONE PRESS, WORKING THE NEXT

R13 << 2 — 3 is 11. Add how many zeros, worth how much?
11, append 00, gives 11003 × 4 = 12
R27 << 1 — 7 is 111. One zero in on the right.
111, append 0, gives 11107 × 2 = 14
R31 << 5 — the flag-builder from the tricks sheet. A lone 1, pushed five lanes up.
1, append 00000, gives 1000001 × 2⁵ = 32
R4100 >> 2 — 100 is 1100100. Erase the last two bits.
1100100, chop 00, gives 11001100 ÷ 4 = 25
R513 >> 1 — 13 is 1101. The chopped bit is a 1 this time. Does it come back?
1101, chop the 1, gives 110 — the 1 is GONE13 ÷ 2 = 6, not 6.5
R6-20 >> 2 — negative in. What does >> pour into the empty left lanes?
sign bit (1) copied in — negative stays negative−20 ÷ 4 = −5

Score yourself out of 6 in the margin. R5 is the one the exam loves: a dropped 1-bit is lost forever — right shift floors, it never rounds.

PART 9 · THE STAR OF THE POSTER >>> JAVA-ONLY

>>> — unsigned right shift, the operator C doesn't have.

Same slide as >>, one change: the vacated left lanes get zeros, always — the sign bit gets no special treatment. On positive numbers you can't tell the twins apart. On negatives, they part ways spectacularly.

James Gosling, the creator of the Java language

THE MAN WHO ADDED IT · JAMES GOSLING · JAVA'S CREATOR

"C's right shift on negatives is a coin toss. Mine isn't."

In C, shifting a negative number right is implementation-defined — different compilers, different answers, same source code. Gosling's team refused to ship that ambiguity: Java defines >> as always sign-filling and added >>> as always zero-filling. Two operators, zero coin tosses — every JVM on earth gives the same answer. That is the exam story of why Java has three shift operators, in one paragraph.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\<you>\Desktop\java-practice\class-04\Unsigned.java
MINI PROBLEM · UNSIGNED.JAVA
PROBLEM
Put the twins >> and >>> side by side — first on a positive number where they agree, then on -8 where sign-fill and zero-fill part ways spectacularly.
REQUIRE­MENTS
  • Class Unsigned, saved as Unsigned.java in class-04 — four println lines.
  • Print 40 >> 2 and 40 >>> 2 (the agreement), then -8 >> 2 and -8 >>> 2 (the split).
EXPECTED OUTPUT
four lines: 10 · 10 · -2 · 1073741822 — same −8, same 2 lanes, one answer negative, the other over a billion.
Unsigned.java — Notepad++
1// Unsigned.java — the twins part ways at zero
2public class Unsigned
3{
4 public static void main(String[] args)
5 {
6 System.out.println(40 >> 2); // positive: twins agree
7 System.out.println(40 >>> 2); // ...identical
8 System.out.println(-8 >> 2); // sign-fill -> small negative
9 System.out.println(-8 >>> 2); // zero-fill -> HUGE positive
10 }
11}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> javac Unsigned.java

C:\Users\diya\Desktop\java-practice\class-04> java Unsigned

10

10

-2

1073741822

Same −8, same 2 lanes — one answer is −2, the other is over a billion. The zeros poured into the top lanes turned a negative pattern into a giant positive one. Self-study Sheet 5 walks the exact 32 bits. ✦

Exam two-liner — "Why does Java have three shift operators?"

"<< shifts left (×2ⁿ). For right shifts Java defines both behaviours C left ambiguous: >> fills with the sign bit (arithmetic, keeps negatives negative) and >>> fills with zeros (logical, treats the bits as unsigned)." Done — full marks, no coin toss.

>>> WORKOUT · THREE MORE ROUNDS — PREDICT IN THE NOTEBOOK, THEN PRESS FOR THE WORKING

W1-1 >>> 28 — recall from Bits.java: −1 is all 32 bits ON. Slide right 28, pour zeros in. What survives?
28 zeros poured in, only the last 4 ones remain: 1111= 15
W2(lo + hi) >>> 1 — the JDK's own binary-search midpoint. Why >>> and not / 2?
if lo + hi overflows into a negative, >>> still lands the true midpointreal production code
W38 >>> 32 — surely sliding an int 32 lanes wipes it to 0?
int shifts use only the low 5 bits of the distance: 32 & 31 = 0= 8, unchanged!

W2 is a genuine line from java.util.Arrays.binarySearch — the first place most programmers meet >>> in the wild. W3 (shift distance mod 32 for int, mod 64 for long) is a standing MCQ trap.

SELF-STUDY · SHEET 5 OF 7

The −8 walkthrough — all 32 bits, no shortcuts.

Part 9 showed you the two answers. This sheet earns them, bit by bit, so the numbers stop being magic. Keep it open next to your ruled notebook and copy each row once — this exact trace is a standing exam question.

BUILD-UP · ONE ROW PER PRESS — 8, THEN −8, THEN BOTH SHIFTS (upper 24 bits shown as one block)

0000…0000
1
0
0
0

+8 is …01000

1111…1111
1
1
0
0

−8: flip all bits of 8, add 1 (two's complement), giving …11000. Sign bit = 1.

1111…1111
1
1
1
0

−8 >> 2: slide right 2, copy the 1 into the top lanes — still all-1s up top, result −2

0
0
1111…1111
1
0

−8 >>> 2: slide right 2, pour zeros into the top lanes — sign bit now 0, result 1,073,741,822

Why so huge, exactly?

The pattern 00111…110 is just below 2³⁰ × 4. Precisely: (2³² − 8) ÷ 4 = 1,073,741,822. The bits didn't change value — the sign bit's meaning did.

Notebook drill

Redo this trace at home for −16 >> 3 and −16 >>> 3. Answers to check yourself: −2 and 536,870,910. If both match, this question can never ambush you.

The one-sentence summary

">> preserves the sign bit; >>> overwrites it with 0 — so on negatives, >> gives a small negative and >>> a large positive." Quote it verbatim.

SELF-STUDY · SHEET 6 OF 7

Shift tricks — the pocket toolkit.

Nobody ships x * 2 as x << 1 for speed anymore — the compiler does that for you. You learn these four idioms because interviews and Class 31's bitmask questions speak this dialect, and you need to read it fluently.

IDIOMMEANINGEXAMPLE
x << nx × 2ⁿ3 << 4 = 48
x >> nx ÷ 2ⁿ (floor, sign kept)-9 >> 1 = −5 (floors down!)
1 << kbuild the k-th flag1 << 3 = 8 (bit 3 only)
(perm & (1 << k)) != 0is flag k on?the Class-31 bitmask test
Set, clear, toggle

Set flag k: perm | (1 << k). Clear it: perm & ~(1 << k). Toggle it: perm ^ (1 << k). Three lines — the entire flags API of half the operating systems you use.

The −9 surprise

-9 / 2 is −4 (truncates toward zero) but -9 >> 1 is −5 (floors toward −∞). On negative odd numbers, shift and divide disagree by one. A cruel but fair MCQ.

Even/odd in one &

(n & 1) == 1 ⇔ n is odd — the last bit is the parity. Same answer as n % 2 != 0, and you'll meet both spellings in code reviews for the rest of your life.

PART 12 · WHO GOES FIRST

The precedence ladder — and the trap that catches half the hall.

Every expression with two operators asks the same question: who binds first? The ladder below answers it, top rank first. You already trust most of it from school — the trap is where shifts sit: below arithmetic.

RANKFAMILYOPERATORSMEMORY HOOK
1Unary++ -- ! ~ (cast)one victim, first strike
2Multiplicative* / %school BODMAS starts
3Additive+ −…and continues
4Shift<< >> >>>BELOW + and − — the trap
5Relational< > <= >=questions after arithmetic
6Equality== !=same/different, judged late
7Bitwise& then ^ then |and-xor-or, in that order
8Logical&& then ||the glue binds loosely
9Ternary? :Sheet 7 · self-study
10Assignment= += -= …always last — stores the result
Trap.java — the exam's favourite line
1int x = 3;
2System.out.println(x + 1 << 2); // most of the hall writes 7…
3// rank 3 (+) beats rank 4 (<<): (x + 1) << 2 = 4 << 2
4System.out.println((x + 1) << 2); // same thing, spelled honestly
5System.out.println(x + (1 << 2)); // what the 7-writers THOUGHT it said
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> java Trap

16

16

7

16, not 7. Addition outranks shift, so x + 1 happens first: 4 << 2 = 16. If you wanted 7, the brackets were YOUR job. ✦

The working rule for this course: memorise three anchors — unary first, assignment last, shifts below arithmetic — and bracket everything else. Nobody, including the people who wrote the compiler, keeps all ten ranks in their head. Brackets cost nothing and read instantly.

PART 13 · YOUR TURN · PREDICTION

Activity 1 — does Rohit qualify for the merit scholarship?

The scholarship rule chains two conditions: attendance >= 75 && cgpa >= 8.5. Below are three students' actual numbers. For each, predict the printed verdict — and, the real question, say which condition short-circuits and which line never even evaluates. Notebook first.

Merit.java — the scholarship gate
1int attendance = sc.nextInt();
2double cgpa = sc.nextDouble();
3boolean merit = attendance >= 75 && cgpa >= 8.5;
4System.out.println("merit: " + merit);

THREE STUDENTS — PREDICT EACH VERDICT

ROHIT:  attendance = 68   cgpa = 9.2
DIYA:   attendance = 91   cgpa = 8.1
KRISH:  attendance = 84   cgpa = 8.9

THE REAL QUESTION

For which student is the cgpa
check NEVER EVEN EVALUATED?

RULED NOTEBOOK FIRST — THREE VERDICTS + ONE SHORT-CIRCUIT CALL

Write "merit: ___" for all three, then one sentence naming whose cgpa Java never reads, and why. Only then unlock.

Predict first — a guess you committed to is worth ten you didn't.

SOLUTION SHEET · ONE STUDENT PER STEP
Merit.java — all three traced
R// ROHIT: 68 >= 75 -> FALSE. && STOPS. cgpa 9.2 NEVER READ. merit: false
D// DIYA: 91 >= 75 -> true, keep going. 8.1 >= 8.5 -> false. merit: false
K// KRISH: 84 >= 75 -> true. 8.9 >= 8.5 -> true. merit: true ✓
// Short-circuit answer: ROHIT — his left side already decided the AND.
THE THREE RUNS

merit: false <- Rohit

merit: false <- Diya

merit: true <- Krish

Diya's case is the subtle one — no short-circuit happened.

Her attendance passed, so Java had to read her cgpa; the false came from the right side, fully evaluated. Short-circuit is not "the answer was false" — it is "the right side never ran". Only Rohit's run did that. That distinction is the mark.

PART 14 · YOUR TURN · FILL IN THE CODE

Activity 2 — Krish's canteen card, three transactions.

Krish's canteen card starts at ₹35. He recharges ₹200, buys a ₹75 lunch, then a ₹40 snack. The program below has three blanks — each one a compound-assignment line. Fill them in, predict the closing balance, then check the terminal.

Canteen.java — three blanks to fill
1int balance = 35;
2// BLANK A: recharge ₹200 — one compound line
3// BLANK B: lunch ₹75 — one compound line
4// BLANK C: snack ₹40 — one compound line
5System.out.println("closing: " + balance);

YOUR TWO JOBS, IN ORDER

1. Write lines A, B, C
   (compound form only — no
    balance = balance + …)
2. PREDICT the closing balance
   before you run anything.

RULED NOTEBOOK FIRST — THREE LINES + ONE NUMBER

Three compound lines and your predicted closing balance. Trace the box after each line: 35, then ?, then ?, then ?

The box trace is the answer — the number just falls out of it.

SOLUTION SHEET · ONE TRANSACTION PER STEP
Canteen.java — blanks filled, box traced
Abalance += 200; // read 35, add 200, store -> 235
Bbalance -= 75; // 235 - 75 -> 160
Cbalance -= 40; // 160 - 40 -> 120
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> java Canteen

closing: 120

35, then 235, then 160, then 120. Same box, three updates in place — the fare-meter pattern, spending edition. ✦

Wrote balance =+ 200? Look again — that compiled and lied.

=+ is not an operator: it parses as balance = (+200) — a plain assignment of positive 200, wiping the 35. Closing balance: 85. No error, wrong money. Compound operators are operator-then-equals, always: +=.

PART 15 · YOUR TURN · CLASSIFICATION

Activity 3 — eight lines from a real electricity-bill calculator.

Below are eight lines lifted straight out of a working domestic-billing program. In your notebook, make four columns — ARITHMETIC · RELATIONAL · LOGICAL · ASSIGNMENT — and file the main operator of each line where it belongs. Careful: two lines contain more than one family; classify what the line is doing.

Bill.java — eight lines to file
1double energy = unitsUsed * rate;
2boolean overBase = unitsUsed > 100;
3boolean heavy = isCommercial && unitsUsed > 500;
4total += surcharge;
5int roundUnits = unitsUsed % 50;
6boolean samePlan = planCode == 7;
7months++;
8boolean exempt = !isCommercial || unitsUsed <= 30;

YOUR FOUR COLUMNS

ARITHMETIC  |  RELATIONAL
LOGICAL     |  ASSIGNMENT

File the MAIN operator of
each of the 8 lines.

RULED NOTEBOOK FIRST — THE FOUR-COLUMN TABLE

Eight line numbers, four columns. For lines 3 and 8, add one clause saying which other family also appears inside.

Two lines are deliberately double-natured — commit before you peek.

SOLUTION SHEET · ONE LINE PER STEP
Bill.java — all eight filed
1// * ............... ARITHMETIC (multiplication)
2// > ............... RELATIONAL (produces a boolean)
3// && .............. LOGICAL — with a RELATIONAL (>) inside its right arm
4// += .............. ASSIGNMENT (compound)
5// % ............... ARITHMETIC (remainder is arithmetic, not "logic")
6// == .............. RELATIONAL (equality — compares, never assigns)
7// ++ .............. ARITHMETIC (unary step — shorthand for months += 1)
8// || with ! ....... LOGICAL — with a RELATIONAL (<=) inside its right arm

THE FINISHED TABLE

ARITHMETIC : 1, 5, 7
RELATIONAL : 2, 6
LOGICAL    : 3, 8
ASSIGNMENT : 4
The two common slips, named.

Filing line 5's % under "logical" because it feels like a test — no: it computes a number. And filing line 6's == under assignment because it contains "=" — no: it asks a question and answers boolean. Family = what the operator produces.

PART 16 · CONTROL FLOW · THE MANY-WAY BRANCH

switch — one value, many doors, and the fall-through rule.

A ladder of if/else if comparing one variable against constants is really a lookup. switch says so honestly: match the value, enter that door. The catch that fills exam papers: without break, execution falls through into the next door and keeps going.

MessMenu.java — Diya's week, day number in
1import java.util.Scanner;
2public class MessMenu
3{
4 public static void main(String[] args)
5 {
6 int day = new Scanner(System.in).nextInt();
7 switch (day)
8 {
9 case 1: System.out.println("Idli & sambar"); break;
10 case 2: System.out.println("Puri bhaji"); break;
11 case 6: // no break — INTENDED fall-through
12 case 7: System.out.println("Biryani special"); break;
13 default: System.out.println("Regular thali");
14 }
15 }
16}
THREE RUNS

C:\Users\diya\Desktop\java-practice\class-04> java MessMenu ⏎ 2

Puri bhaji

C:\Users\diya\Desktop\java-practice\class-04> java MessMenu ⏎ 6

Biryani special

C:\Users\diya\Desktop\java-practice\class-04> java MessMenu ⏎ 4

Regular thali

Day 6 entered an empty case and fell straight through into case 7 — both weekend days share one biryani line. Fall-through as a feature, on purpose, commented. ✦

The three rules of switch

The selector is one value (int, char, String…). Each case label is a constant, not a range. And execution runs from the matched label until a break — or the closing brace.

Fall-through: tool AND trap

Cases 6–7 sharing biryani is fall-through used well. Forgetting a break so one day also prints another day's menu is the same mechanism used badly — Activity 4 hands you exactly that bug.

Java 14+ has a cleaner spelling

case 6, 7 -> "Biryani special"; — the arrow form: no fall-through possible, no break needed. Worth recognising on sight; this course examines the classic form.

Why not just if/else if? You could — the two are interchangeable here. The difference is intent: switch tells the reader "one value, fixed menu of answers" at a glance, and the compiler can jump straight to the right door instead of testing every rung. When the question is "which of N known values?", reach for switch.

SELF-STUDY · SHEET 7 OF 7

The ternary ? : — an if/else that fits inside an expression.

Read condition ? a : b aloud as a question: "condition? then a — otherwise b." It is the only Java operator that takes three operands, and its whole job is choosing a value, right where that value is needed.

Ternary.java — Notepad++
1// Ternary.java — choose a value, in place
2public class Ternary
3{
4 public static void main(String[] args)
5 {
6 int marks = 78;
7 String verdict = marks >= 35 ? "PASS" : "FAIL";
8 System.out.println(verdict);
9 int a = 42, b = 87;
10 System.out.println("bigger: " + (a > b ? a : b));
11 }
12}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> javac Ternary.java

C:\Users\diya\Desktop\java-practice\class-04> java Ternary

PASS

bigger: 87

Line 7 is an if/else squeezed into the right-hand side of an assignment — something a real if can never do, because if is a statement, not a value. ✦

When to use it

One condition, two values, result feeding straight into an assignment or a println — ternary. The max-of-two idiom a > b ? a : b is its signature move.

When NOT to use it

Two actions (print this, also update that), or nested ternaries three questions deep. The moment a reader must squint, you owed them an if/else. Readability outranks cleverness.

On the ladder

Rank 9 — below the logicals, above only assignment. So x = a > b ? a : b; needs no brackets: the comparison, then the choice, then the store. Exactly the reading order.

PART 18 · CONTROL FLOW · THE LOOP THAT ASKS FIRST

do-while — the UPI PIN screen that must appear at least once.

Open PhonePe or GPay: the PIN pad shows up before the app knows whether you'll type it right. Ask first, check after — that is do-while, the loop whose body is guaranteed to run at least once. A plain while checks first and might never ask at all.

PinCheck.java — ask first, judge after
1import java.util.Scanner;
2public class PinCheck
3{
4 public static void main(String[] args)
5 {
6 Scanner sc = new Scanner(System.in);
7 int correctPin = 4271; // numeric PIN — an int box
8 int enteredPin;
9 do
10 {
11 System.out.print("Enter UPI PIN: ");
12 enteredPin = sc.nextInt();
13 }
14 while (enteredPin != correctPin); // int == int — judged AFTER the ask
15 System.out.println("Payment authorised.");
16 }
17}
ONE STUBBORN RUN

C:\Users\diya\Desktop\java-practice\class-04> java PinCheck

Enter UPI PIN: 1234

Enter UPI PIN: 4217

Enter UPI PIN: 4271

Payment authorised.

The pad appeared before any judging, then reappeared exactly as long as the answer was wrong. Body first, condition after — the do-while signature. ✦

while vs do-while, one line each

while: check, maybe run — 0 or more times. do-while: run, then check — 1 or more times. Menus, PIN pads, "play again?" prompts: anything that must ask once is do-while turf.

The semicolon that IS required

while (…); at the bottom of a do-while needs its semicolon — the one place where while takes one. (After a normal while (…) header, that same semicolon is the classic empty-loop bug.)

Why int ==, not a String?

The PIN lives in an int box, so == compares values directly — clean and correct. If the PIN were a String, comparison would need .equals() — a method with its own story, taught properly in Class 27 (j414). Until then: numeric PINs, numeric compare.

PART 19 · CONTROL FLOW · THE EMERGENCY EXITS LABELLED BREAK · JAVA-SPECIFIC

break leaves, continue skips — and a label leaves both loops.

Two small words steer any loop from inside: break abandons the loop entirely; continue abandons only this pass and jumps to the next. Then Java adds one move C's break doesn't have: name a loop with a label, and break out of the outer loop from deep inside the inner one.

Basics.java — the two words in one loop
1for (int i = 1; i <= 8; i++)
2{
3 if (i % 2 == 0) continue; // even? skip THIS pass only
4 if (i == 7) break; // 7? abandon the WHOLE loop
5 System.out.print(i + " ");
6}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> java Basics

1 3 5

Evens skipped by continue; the moment i hit 7, break ended everything — 7 itself never printed. Skips are per-pass, breaks are forever. ✦

THE JAVA MOVE · SEARCHING THE COLLEGE BUS FOR ONE EMPTY SEAT — BOTH LOOPS STOP THE INSTANT IT'S FOUND

BusSeat.java — labelled break over a 2D chart
1int[][] bus = { // 1 = taken, 0 = empty · 3 rows × 4 seats
2 {1, 1, 1, 1},
3 {1, 1, 0, 1}, // <- row 1, seat 2 is free
4 {1, 0, 1, 1} };
5search: // the LABEL — names the outer loop
6for (int r = 0; r < bus.length; r++)
7{
8 for (int s = 0; s < bus[r].length; s++)
9 {
10 if (bus[r][s] == 0)
11 {
12 System.out.println("Row " + r + ", seat " + s);
13 break search; // leaves BOTH loops, instantly
14 }
15 }
16}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-04> java BusSeat

Row 1, seat 2

One line printed, then silence — row 2's free seat was never visited. A plain break would only exit the inner loop, and row 2 would print too. The label made the exit TOTAL. ✦

The label, precisely

A name and a colon (search:) directly before a loop. break search; then means "exit the loop named search" — however deep you currently are. continue search; exists too: next pass of the outer loop.

C doesn't have this

C escapes nested loops with goto or a flag variable checked in every header. Java's labelled break gives you the clean exit without goto's chaos — the second Java-specific star of today, after >>>.

Class 3 pays rent

bus is the 2D array from your self-study sheets — rows of rows, walked with nested loops, sized by .length at both depths. Today just added the emergency exit.

PART 20 · YOUR TURN · TRACE, THEN DEBUG

Activity 4 — the grade band that prints two grades.

A grade-band switch is missing exactly one break. For a student with band 8 (marks 80–89), it prints two grades for the same mark. Trace which case runs, what falls through, and what the terminal shows — in your notebook, before unlocking.

GradeBand.java — one break short
1int band = marks / 10; // 87 -> band 8 (int division!)
2switch (band)
3{
4 case 10:
5 case 9: System.out.println("Grade A+"); break;
6 case 8: System.out.println("Grade A"); // <- something is missing here
7 case 7: System.out.println("Grade B"); break;
8 default: System.out.println("Grade C or below");
9}

TRACE FOR marks = 87

1. Which case label matches?
2. Which println lines run,
   IN ORDER?
3. Where does execution
   finally stop, and why?

RULED NOTEBOOK FIRST — THE EXACT TERMINAL OUTPUT

Write the terminal output line by line for marks = 87, then one sentence naming the mechanism and the one-word fix.

Fall-through was taught two parts ago — trust your trace.

SOLUTION SHEET · THE TRACE, STEP BY STEP
GradeBand.java — the walk of marks = 87
1// 87 / 10 -> 8 (int division truncates — Sheet 1 again)
2// switch jumps to case 8 -> prints "Grade A"
3// NO break -> execution FALLS THROUGH into case 7 -> prints "Grade B"
4// case 7 DOES have a break -> NOW it stops. Two grades, one student.
FIX case 8: System.out.println("Grade A"); break;
BEFORE AND AFTER

C:\Users\diya\Desktop\java-practice\class-04> java GradeBand (buggy)

Grade A

Grade B

C:\Users\diya\Desktop\java-practice\class-04> java GradeBand (with the break)

Grade A

Note what did NOT happen: no error, no warning. Fall-through is legal Java — the compiler can't know cases 6–7 in Part 16 were intended and this one wasn't. Only your break says so. ✦

ACTIVITY 5 · DEBUGGING · THE LOOP THAT NEVER EXITS

The PIN pad that never gives up — or locks anyone out.

Someone "improved" Part 18's PIN loop with a 3-attempt limit — and now wrong PINs make it loop forever. It compiles cleanly. Read the code like the JVM does, pass by pass, and find why attempts never reaches 3.

PinRetry.java — compiles, never exits
1int correctPin = 4271;
2int enteredPin;
3do
4{
5 int attempts = 0; // hmm… WHERE is this box born?
6 System.out.print("Enter UPI PIN: ");
7 enteredPin = sc.nextInt();
8 attempts++;
9}
10while (enteredPin != correctPin && attempts < 3);

THREE QUESTIONS, IN ORDER

1. What is attempts worth at
   line 8, on EVERY pass? Why?
2. Wait — line 10 reads attempts.
   Does that even COMPILE? (Think
   Class 3: scope = the { } room.)
3. Fix it with ONE moved line.

RULED NOTEBOOK FIRST — NAME THE ROOM, THEN MOVE THE LINE

Answer all three questions. Question 2 is the deep one — it decides whether this bug is a runtime loop or something the compiler already caught.

Scope from Class 3 + do-while from today — everything you need is already yours.

SOLUTION SHEET · THE ROOM, THE RESET, THE FIX
PinRetry.java — fixed
1int attempts = 0; // MOVED OUT — born once, BEFORE the loop
2do
3{
4 System.out.print("Enter UPI PIN: ");
5 enteredPin = sc.nextInt();
6 attempts++; // now it truly counts: 1, 2, 3…
7} while (enteredPin != correctPin && attempts < 3);
FIXED RUN · THREE WRONG TRIES

C:\Users\diya\Desktop\java-practice\class-04> java PinRetry

Enter UPI PIN: 1111

Enter UPI PIN: 2222

Enter UPI PIN: 3333

Card blocked. Visit your branch.

Three asks, then the loop let go — attempts finally kept its count between passes, because it now lives OUTSIDE the room that gets demolished each pass. ✦

The full answer to Question 2 — and the honest subtlety.

In the buggy version, attempts is declared inside the do { } room, and that room's boxes are demolished at the closing brace — so it resets to 0 and then steps to 1 on every pass, never reaching 3. Sharper still: because the box dies at }, the condition on line 10 cannot even see it — javac stops you with cannot find symbol. Scope (Class 3) explains the compile error; the reset explains why the "fixed-by-moving-the-print" versions people try still loop forever. One moved line answers both.

PART 21 · BEFORE YOU GO

Your folder, your homework — and the road to Lab 0 is clear.

Today was the longest class in the unit for a reason: it finished the toolkit. Every operator, every branch, every loop Lab 0 will ask of you has now been taught, traced and debugged with your own pen.

YOUR FOLDER AFTER THIS CLASS — CHECK BEFORE YOU LEAVE
Desktop\java-practice\class-04\
LeapYear.java <- worked ex. 1 · the 400-year condition
LeapYear.class <- javac made it
FareMeter.java <- worked ex. 2 · += leg by leg
FareMeter.class
MessMenu.java <- worked ex. 3 · fall-through on purpose
MessMenu.class
PinCheck.java <- do-while · asks at least once
PinCheck.class
GradeBand.java <- activity 4 · with YOUR break in it
GradeBand.class <- proof the fix compiled
PinRetry.java <- activity 5 · attempts moved OUT of the room
PinRetry.class

HOMEWORK · DUE BEFORE LAB 0

1 Write & run OddSum.java

Read one int n, sum the odd numbers from 1 to n with a for loop, a continue for evens, and += for the total. Test with n = 10 — you must see 25.

2 Paper drill: the shift traces

No code — ruled notebook. Trace −16 >> 3 and −16 >>> 3 the Sheet-5 way, all lanes. Check yourself: −2 and 536,870,910. Then write the two-sentence "why three shifts?" answer from memory.

3 Re-read Sheets 1–3 + the Lab 0 prelab, before lab day

Lab 0's four prelab programs (Scanner, arithmetic, if/else, a counting for-loop) rehearse exactly today's and Class 3's material. Thirty minutes of revision buys you a calm two hours in the lab.

Homework 1 and 2 solved below — your run and your paper trace first, then compare.

HOMEWORK SOLUTIONS · HW 1 CODE + HW 2 SHIFT TRACES
OddSum.java — for, continue and += doing exactly their jobs
1import java.util.Scanner;
2public class OddSum
3{
4 public static void main(String[] args)
5 {
6 Scanner sc = new Scanner(System.in);
7 System.out.print("n: ");
8 int n = sc.nextInt();
9 int total = 0;
10 for (int i = 1; i <= n; i++)
11 {
12 if (i % 2 == 0) continue;
13 total += i;
14 }
15 System.out.println("Odd sum = " + total);
16 }
17}
THE n = 10 TEST

C:\Users\diya\Desktop\java-practice\class-04> javac OddSum.java

C:\Users\diya\Desktop\java-practice\class-04> java OddSum

n: 10

Odd sum = 25

1 + 3 + 5 + 7 + 9 = 25. If you saw 30, your continue skipped odds instead of evens — check the == 0. If you saw 55, the continue never fired at all.

HW 2 · the shift traces, checked. −16 >> 3: arithmetic shift copies the SIGN bit in from the left, so the answer stays negative — −16 ÷ 2³ = −2. −16 >>> 3: zero-fill shift pushes 0s in from the left, the sign bit is destroyed, and the huge positive 536,870,910 appears.

The two-sentence "why three shifts?" model answer.

<< multiplies by 2 per step and >> divides while PRESERVING the sign, so signed arithmetic stays correct. >>> exists for when the 32 bits are a raw pattern, not a number — it fills with zeros regardless of sign, which C cannot express and Java added.