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.
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
switchand 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 ≥ 1break&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
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.
/ truncates, % keeps the leftover, and one 6.0 rescues the paise. Then let seat++ vs ++seat show their before/after difference.- Class
Arith, saved asArith.javainclass-04; start withint fee = 4750, months = 6; - Print
fee / months, thenfee % months, thenfee / 6.0— three separate lines. - Declare
int seat = 41;then printseat++and++seaton their own lines.
791 · 4 · 791.6666666666666 · 41 · 43.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. ✦
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.
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.
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.
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.
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.
| A | B | A && B | A || B | SHORT-CIRCUIT? |
|---|---|---|---|---|
| true | true | true | true | — |
| false | anything | false | B decides | && never reads B |
| true | anything | B decides | true | || never reads B |
! flips one boolean: !true gives false. That's the whole operator. | ||||
classesHeld = 0. Both attendance checks divide by that zero on paper — prove that short-circuit && and || stop reading before the division ever runs.- Class
Guard, saved asGuard.javainclass-04; start withint classesHeld = 0, attended = 0; shortAtt: guardclassesHeld > 0on 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.
attendance short? false then can sit exam? true — no exception, ever.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. ✦
== != < > <= >= — 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.
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.
"&& 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.
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.
b += 1 compile where b = b + 1 refuses.- Class
TopUp, saved asTopUp.javainclass-04; start withint balance = 150; - Apply
+= 500(recharge),-= 265(data pack),-= 80(caller tune) — no second variable. - Print
left:+ balance; then declarebyte b = 10;and print it afterb += 1;
left: 305 then 11.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. ✦
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.
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.
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.
% in one boolean line.- Class
LeapYear, saved asLeapYear.javainclass-04; importjava.util.Scanner. - Read one int with
nextInt(); compute(y % 4 == 0 && y % 100 != 0) || y % 400 == 0into one boolean. - Print the year, the text
leap?, and the boolean on one line.
2024 prints 2024 leap? true · 1900 prints 1900 leap? false · 2000 prints 2000 leap? true.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.
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.
+= — the accumulator pattern, no fare1/fare2/fare3 clutter.- Class
FareMeter, saved asFareMeter.javainclass-04; importjava.util.Scanner. - Start with
double fare = 50.0;(base) anddouble perKm = 12.0; - Read three leg distances with
nextDouble(); fold each in withfare += perKm * … - Print
Total = Rs.+ fare.
3.5, 2.0, 6.5 — the meter grows 50, then 92, then 116, and prints Total = Rs.194.0.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. ✦
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.
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.
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.
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 a | bit b | a & b | a | b | a ^ b |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
BUILD-UP · 12 & 10, ONE LANE PER PRESS — ONLY DOUBLE-1 SURVIVES
a = 12, binary 1100
b = 10 is 1010
a & b gives 1000 = 8 — only the leftmost lane had 1 AND 1
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.- Class
Bits, saved asBits.javainclass-04; declareint a = 12, b = 10; - Print
a & b,a | b,a ^ b, and~a— four lines, same two numbers.
8 · 14 · 6 · -13 (flipping all 32 bits of n gives −(n+1)).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. ✦
& works on bits of numbers, && on booleans — and only && short-circuits. Mixing them up in a condition compiles sometimes and burns you always.
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.
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
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
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.
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
5 is 0101
5 << 1 gives 1010 = 10 — everyone slides left, a fresh 0 fills the right. One lane left = ×2.
- Class
Shifts, saved asShifts.javainclass-04— no variables needed, four println lines. - Print
5 << 1,5 << 3,40 >> 2, then-40 >> 2.
10 · 40 · 10 · -10 — the sign bit was copied in, so negative in, negative out.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. ✦
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.
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.
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
3 << 2 — 3 is 11. Add how many zeros, worth how much?7 << 1 — 7 is 111. One zero in on the right.1 << 5 — the flag-builder from the tricks sheet. A lone 1, pushed five lanes up.100 >> 2 — 100 is 1100100. Erase the last two bits.13 >> 1 — 13 is 1101. The chopped bit is a 1 this time. Does it come back?-20 >> 2 — negative in. What does >> pour into the empty left lanes?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.
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.
>> and >>> side by side — first on a positive number where they agree, then on -8 where sign-fill and zero-fill part ways spectacularly.- Class
Unsigned, saved asUnsigned.javainclass-04— four println lines. - Print
40 >> 2and40 >>> 2(the agreement), then-8 >> 2and-8 >>> 2(the split).
10 · 10 · -2 · 1073741822 — same −8, same 2 lanes, one answer negative, the other over a billion.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. ✦
"<< 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
-1 >>> 28 — recall from Bits.java: −1 is all 32 bits ON. Slide right 28, pour zeros in. What survives?(lo + hi) >>> 1 — the JDK's own binary-search midpoint. Why >>> and not / 2?8 >>> 32 — surely sliding an int 32 lanes wipes it to 0?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.
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)
+8 is …01000
−8: flip all bits of 8, add 1 (two's complement), giving …11000. Sign bit = 1.
−8 >> 2: slide right 2, copy the 1 into the top lanes — still all-1s up top, result −2
−8 >>> 2: slide right 2, pour zeros into the top lanes — sign bit now 0, result 1,073,741,822
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.
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.
">> preserves the sign bit; >>> overwrites it with 0 — so on negatives, >> gives a small negative and >>> a large positive." Quote it verbatim.
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.
| IDIOM | MEANING | EXAMPLE |
|---|---|---|
x << n | x × 2ⁿ | 3 << 4 = 48 |
x >> n | x ÷ 2ⁿ (floor, sign kept) | -9 >> 1 = −5 (floors down!) |
1 << k | build the k-th flag | 1 << 3 = 8 (bit 3 only) |
(perm & (1 << k)) != 0 | is flag k on? | the Class-31 bitmask test |
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.
-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.
(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.
| RANK | FAMILY | OPERATORS | MEMORY HOOK |
|---|---|---|---|
| 1 | Unary | ++ -- ! ~ (cast) | one victim, first strike |
| 2 | Multiplicative | * / % | school BODMAS starts |
| 3 | Additive | + − | …and continues |
| 4 | Shift | << >> >>> | BELOW + and − — the trap |
| 5 | Relational | < > <= >= | questions after arithmetic |
| 6 | Equality | == != | same/different, judged late |
| 7 | Bitwise | & then ^ then | | and-xor-or, in that order |
| 8 | Logical | && then || | the glue binds loosely |
| 9 | Ternary | ? : | Sheet 7 · self-study |
| 10 | Assignment | = += -= … | always last — stores the result |
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.
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.
merit: false <- Rohit
merit: false <- Diya
merit: true <- Krish
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.
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.
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. ✦
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.
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.
THE FINISHED TABLE
ARITHMETIC : 1, 5, 7 RELATIONAL : 2, 6 LOGICAL : 3, 8 ASSIGNMENT : 4
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.
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 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.
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.
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.
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.
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. ✦
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.
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.
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.
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: 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.
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.)
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.
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
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. ✦
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 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 >>>.
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.
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.
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.
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.
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. ✦
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.
HOMEWORK · DUE BEFORE LAB 0
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.
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.
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.
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.
<< 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.