UI24PC320CS · OOP THROUGH JAVA · UNIT I · LAB 0 · AFTER CLASS 4 EXACTLY
Everything is taught.
Now you type.
Four classes gave you println, Scanner, data types, arrays and every operator, branch and loop. Lab 0 asks for nothing new — it asks for your fingers. Four small programs at home before lab day, three exercises in the lab. Seven programs, one folder, two hours.
STEP 0 · BEFORE ANY CODE — MAKE THE FOLDER, SO EVERY FILE HAS A HOME
C:\Users\diya> cd Desktop\java-practice
C:\Users\diya\Desktop\java-practice> mkdir lab-00
C:\Users\diya\Desktop\java-practice> cd lab-00
C:\Users\diya\Desktop\java-practice\lab-00> _
That last prompt is your working directory — every javac and java in this lab runs from exactly here. If your prompt doesn't end in lab-00, stop and cd until it does. ✦
Why the professor is strict about this: when the external examiner asks you to show your Lab 0 work, "it's somewhere on the Desktop" is not an answer. One course folder, one lab subfolder, filenames exactly as printed on the next table — that habit is worth more marks across the semester than any single program.
THE COMPLETE FILE PLAN · 7 PROGRAMS
Four rehearsals at home, three performances in the lab.
Each prelab program mirrors one lab exercise on purpose — same shape, smaller stakes. Do the prelab honestly and lab day is déjà vu, not panic.
| # | FILE (EXACT NAME) | WHEN | MECHANICS | REHEARSES FOR |
|---|---|---|---|---|
| 1 | PrintName.java | PRELAB · HOME | Scanner + println | Exercise 1 |
| 2 | SquareScanner.java | PRELAB · HOME | Scanner + arithmetic | Exercise 2 |
| 3 | EvenOrOdd.java | PRELAB · HOME | Scanner + if/else | Exercise 3 |
| 4 | CountEvens.java | PRELAB · HOME | for + if + count++ | Exercise 3's counters |
| 5 | HelloStudent.java | LAB DAY · EX 1 | Scanner + println banner | — |
| 6 | SimpleCalculator.java | LAB DAY · EX 2 | Scanner + all five arithmetic ops | — |
| 7 | PassFailChecker.java | LAB DAY · EX 3 | array + for + if/else + passCount++/failCount++ | — |
Every solution sheet in every lab renders as non-copyable text. That is not meanness: the entire point of a warm-up lab is the path from your eyes through your fingers to the keyboard. Type every character, including the ones you think you'd never mistype. Muscle memory is the deliverable.
PRELAB THEORY · AT HOME · RULED NOTEBOOK OUT
Five questions before you touch the keyboard.
Pen first, always. The first three are guided — each carries a hint pointing back at the exact class that taught it. The last two are independent — no hint, because the exam won't bring one either. Model answers are on a later page, locked; earn them.
You have just saved PrintName.java in your lab-00 folder. Write the two commands, in order, that turn that file into output on the screen — and say in one phrase what each command does.
.class?YOUR RULED NOTEBOOK — WRITE BOTH COMMANDS + ONE PHRASE EACH
In the line int marks = kb.nextInt(); — name what each of the three pieces does: int marks, kb, and nextInt().
YOUR RULED NOTEBOOK — THREE PIECES, ONE LINE EACH
What exactly does System.out.println(7 / 2); print — and why is the answer not 3.5?
int ÷ int do to the part after the decimal point — round it, or throw it away?YOUR RULED NOTEBOOK — THE PRINTED VALUE + ONE-SENTENCE WHY
A number is stored in an int box called n. Write the exact condition — the part inside if (…) — that is true when n is even. No hint on this one.
YOUR RULED NOTEBOOK — THE CONDITION, CHARACTER BY CHARACTER
How many times does for (int i = 1; i <= 5; i++) run its body — and list every value i takes inside that body. No hint on this one either.
YOUR RULED NOTEBOOK — THE COUNT + EVERY VALUE OF i
Done all five in pen? Good. Don't peek ahead for answers — there are five more questions first, on the next page, and they're the ones lab day silently depends on.
PRELAB THEORY · FIVE MORE · THE ONES LAB DAY SILENTLY DEPENDS ON
Five more — one for each way lab day can bite.
How to use this page: same contract as before — pen answers in your ruled notebook, hints only on the guided three, nothing unlocked until you've committed ink. Each of these five rehearses a fluency the three lab exercises assume without saying so: the compile artefact, switch fall-through, off-by-one bounds, hand-tracing a counter, and what System.in actually is.
In one sentence: what does javac produce, and where does that new file appear?
dir and saw one more file than you had typed. What was its extension, and which folder was it sitting in?YOUR RULED NOTEBOOK — ONE SENTENCE, BOTH HALVES
Only case 3 has a break. day is 2. Write every line this prints, in order:
break, execution falls through the floor of its case into the next one — where does the falling stop here?YOUR RULED NOTEBOOK — EVERY PRINTED LINE, IN ORDER
This loop was meant to print 1 to 10. It prints 1 to 11. Circle the exact characters at fault and write the fix:
for header out loud: "keep going while i is less than or equal to…" — to what?YOUR RULED NOTEBOOK — THE FAULTY CHARACTERS + THE FIXED HEADER
Fill a pass-by-pass table for i and sum — one row per loop pass, then a final row for the printed value. No hint.
YOUR RULED NOTEBOOK — TABLE: PASS · i · sum, THEN THE PRINT
Why does Scanner need System.in as its argument — and not just in? Two sentences, your own words. No hint.
YOUR RULED NOTEBOOK — TWO SENTENCES
Bring this page to lab. Your tutor will spot-check two of these five at the door — in your handwriting, not on your screen. The model answers come next, locked; open them only after all ten questions carry ink.
SOLUTION SHEET · EXTRA FIVE · ANSWER + REASONING + THE COMMON SLIP
Model answers — extra five.
Per the solution-sheet contract, this page is separate from the questions on purpose — you cannot glance sideways at an answer. Each card gives the correct answer, the reasoning, the common slip with the real message your machine shows, and one sentence to keep.
All five answered in pen? Then compare — differences are findings, not failures.
- Answer:
javacproduces a .class file of bytecode — forPrintName.javait createsPrintName.class— in the same folder you compiled from, yourlab-00working directory. - Reasoning: the compiler doesn't run anything; it translates your source into the JVM's language and writes that translation next to the source.
- Common slip: saying "javac runs the program". Type
javac PrintName.classand the real console answerserror: file does not contain class PrintName.class— javac only eats.java. - Keep this: javac makes the .class; java runs it — two verbs, two commands.
- Answer: two lines —
TuethenWed— and nothing else. - Reasoning:
day == 2enters atcase 2, prints Tue, finds nobreak, falls through intocase 3, prints Wed, hitsbreak, leaves.case 1never entered;case 4never reached. - Common slip: answering only
Tue— treating every case as if it auto-stops. Java's switch keeps flowing until abreak, the exact behaviour Class 4's MessMenu used on purpose. - Keep this: a case without break is a room without a floor.
- Answer: the fault is the two characters
11in the middle slot. Fix:for (int i = 1; i <= 10; i++)— or equivalentlyi < 11. - Reasoning:
i <= 11keeps the body alive wheniis 11, so 11 prints. The loop's condition, not its intention, decides the last pass. - Common slip: "fixing" the wrong slot — changing
i = 1toi = 0, which prints 0…11: twelve lines, two of them wrong. - Keep this: off-by-one bugs live in the condition — read it aloud before you run.
- Answer: Pass 1: i=1, sum=1 · Pass 2: i=2, sum=3 · Pass 3: i=3, sum=6 · Pass 4: i=4, sum=10 · then
ibecomes 5,5 <= 4is false, and it prints 10. - Reasoning: each pass adds the current i to sum before i++ steps it. One row per pass — exactly how you'll debug
PassFailCheckerif its counters drift. - Common slip: writing sum=1,2,3,4 — adding 1 each pass instead of adding i. If your last row says sum=4, you traced the ++ and not the +.
- Keep this: trace what the line says, not what you'd have written.
- Answer:
Scanneris a general reader — file, string or keyboard — so it must be told which source to read.System.inis the ready-made object representing the keyboard's input stream; a bareinis just an undeclared name. - Reasoning:
inonly means something as a field of theSystemclass — the dot is the address. - Common slip: typing
new Scanner(in). The real compiler sayserror: cannot find symbol — symbol: variable in. Java never guesses whichinyou meant. - Keep this: System.in is the keyboard, spelled with its full address.
SOLUTION SHEET · FIRST FIVE · ONE REVEAL PER QUESTION
Model answers — the first five, one at a time.
Same lock, same rule: ink first. Each question has its own reveal — open one only after that attempt exists in your notebook. Below the five, three slips that show up in every batch's Lab 0 — read them during the prelab so on lab day they're someone else's.
Your Q1 in pen first — then open this one, and only this one.
- Answer: first
javac PrintName.java, thenjava PrintName. - Reasoning:
javaccompiles your source intoPrintName.classbytecode;javastarts the JVM and runs that bytecode. - Common slip:
java PrintName.java— the run command takes the class name with no extension in this workflow. - Keep this: javac eats a file, java eats a class.
int marks: makes an int-shaped box named marks.kb: your Scanner object — the reader standing at the keyboard.nextInt(): asks that reader to fetch the next whole number the user types and hand it over for storage in the box.- Keep this: box · reader · fetch — three parts, three jobs.
- Answer: it prints 3.
- Reasoning: both 7 and 2 are ints, so Java performs integer division and truncates the .5 — throws it away, no rounding — before println ever sees the value.
- To get 3.5: put a double in the mix —
7 / 2.0. - Keep this: int ÷ int stays int; the decimal never existed.
- Answer:
if (n % 2 == 0) - Reasoning: the remainder after dividing by 2 is zero exactly when n is even.
- Common slip: a single
=— that's assignment, and the compiler rejects it here witherror: incompatible types: int cannot be converted to boolean. - Keep this: both characters of
==matter — one asks, one overwrites.
- Answer: the body runs 5 times, with i = 1, 2, 3, 4, 5.
- Reasoning: when i++ makes i equal 6, the check
6 <= 5fails and the loop ends. - The subtlety: i touches 6, but the body never sees it — the condition is checked before every pass.
- Keep this: count the passes the condition lets through, not the values i visits.
AND THE 3 SLIPS EVERY BATCH MAKES — READ THESE NOW, NO LOCK
- The slip: saving
printname.javafor a class namedPrintName. - Real message:
error: class PrintName is public, should be declared in a file named PrintName.java - The rule: file name = class name, capital for capital — Windows forgives case, Java does not.
- The slip: your file is in
lab-00but your prompt saysC:\Users\diya>. - Real message:
error: file not found: PrintName.java - The rule: the terminal only sees the folder it is standing in — check the prompt before blaming the code.
- The slip: you edit the .java, run
java PrintNameagain, and "nothing changed". - Why: nothing did — you re-ran the old .class. Every edit needs its javac before its java.
- Rhythm to keep: edit, save, javac, java — in that order, every time.
PRELAB CODING · AT HOME · 20–25 MINUTES · NO CODE GIVEN — THAT'S THE POINT
Four small programs, each a rehearsal for one exercise.
Every task below is a mini problem statement: problem, requirements, a sample run to match, and a plan line for your notebook. No code on this page — you write it. The tutor solves all four live at the start of lab (next page), so arrive with attempts, not excuses.
- Class named exactly
PrintName, saved asPrintName.javainlab-00. - Print the prompt
Enter your name: - Read one word with Scanner's
next(). - Print exactly one line:
Hello,followed by the name and!
Diya program prints Hello, Diya! — match it character for character, comma and space included.- Class
SquareScanner, saved asSquareScanner.java. - Prompt
Enter a number: - Read one int with
nextInt(). - Print
Square =followed by n × n.
12 Square = 144.nextInt() instead of next(), and n*n in the println. Notice the reuse; that's the rehearsal working.- Class
EvenOrOdd, saved asEvenOrOdd.java. - Prompt
Enter a number: - Read one int.
- If it's even print
EVEN, otherwise printODD— using the very condition you wrote for theory Q4.
7 ODD · run it twice more with 0 and 44 — 0 must say EVEN.if (n % 2 == 0) two printlns in two branches. Test the boundary (0) — lab day will.passCount++ muscle, one day early.- Class
CountEvens, saved asCountEvens.java. - No Scanner this time — a
forloop from 1 to 20. - Inside it, an
ifwith your even condition andcount++when it's true. - After the loop, print
Evens found:and the count.
Evens found: 10 — if you see 11, revisit theory Q3; your bounds slipped.int count = 0 BEFORE the loop (Class 4's Act 5 taught you why — scope ends at the brace) loop if count++ println after.Stop, write in your notebook which line refused to work and what the console said, and move to the next task. A precise description of where you got stuck earns walkthrough attention on lab day; a blank folder earns nothing.
LAB DAY · FIRST 25 MINUTES · TUTOR AT THE FRONT MACHINE
The walkthrough — your four rehearsals, solved live.
Lab day opens with your tutor building all four prelab programs on the projector, one line per press. Compare each against your homework version as it grows — differences in variable names are taste; differences in structure are your revision list.
WALKTHROUGH 1 OF 4 · Scanner + println
- Class
PrintName; promptEnter your name:withprint(cursor waits on the same line). - Read one word with
next(); printHello,+ name +!
Diya — program answers Hello, Diya! — comma and space exactly.C:\Users\diya\Desktop\java-practice\lab-00> javac PrintName.java
C:\Users\diya\Desktop\java-practice\lab-00> java PrintName
Enter your name: Diya
Hello, Diya!
Line 7 used print, not println — so the cursor waits on the same line as the prompt. Small detail, professional feel. ✦
WALKTHROUGH 2 OF 4 · Scanner + arithmetic
- Class
SquareScanner; promptEnter a number:; read one int withnextInt(). - Print
Square =followed by n × n.
12 — program answers Square = 144.C:\Users\diya\Desktop\java-practice\lab-00> javac SquareScanner.java
C:\Users\diya\Desktop\java-practice\lab-00> java SquareScanner
Enter a number: 12
Square = 144
Why 144 and not "Square = 12*12"? Because * binds tighter than + — multiplication first, then the string glue. Class 4's ladder, already earning rent. ✦
WALKTHROUGH 3 OF 4 · Scanner + if/else
- Class
EvenOrOdd; promptEnter a number:; read one int. if (n % 2 == 0)printEVEN, otherwise printODD.
7 gives ODD · 0 gives EVEN (the boundary must behave).C:\Users\diya\Desktop\java-practice\lab-00> javac EvenOrOdd.java
C:\Users\diya\Desktop\java-practice\lab-00> java EvenOrOdd
Enter a number: 7
ODD
C:\Users\diya\Desktop\java-practice\lab-00> java EvenOrOdd
Enter a number: 0
EVEN
Ran twice — no recompile between runs, because the code didn't change. And 0 says EVEN: 0 % 2 is 0. The boundary behaves. ✦
WALKTHROUGH 4 OF 4 · for + if + count++ (EXERCISE 3'S MUSCLE)
passCount++ counting muscle Exercise 3 needs.- Class
CountEvens; no Scanner — aforloop from 1 to 20. - Declare
int count = 0;BEFORE the loop;count++inside anifwith the even condition. - After the loop, print
Evens found:and the count.
Evens found: 10 — 11 means your bounds slipped.C:\Users\diya\Desktop\java-practice\lab-00> javac CountEvens.java
C:\Users\diya\Desktop\java-practice\lab-00> java CountEvens
Evens found: 10
If your homework printed 11, your loop header said <= 21 or started at 0 — the theory-Q3 bug wearing a different shirt. Fix it now, before Exercise 3 inherits it. ✦
Walkthrough over — screens down. From here the projector goes dark and the next three briefs are yours alone. Everything you're about to type, you have now seen twice: once in class, once on this wall.
EXERCISE 1 OF 3 · 15 MINUTES · 20 MARKS · YOU ALONE
Exercise 1 — HelloStudent.java
No code on this screen — that's deliberate. You built PrintName.java at home and watched it again twenty minutes ago. Same shape, one extra read, one banner.
PROBLEM The lab's attendance system greets each student with a three-line banner built from their own details.
REQUIREMENTS ① Class named exactly HelloStudent. ② Prompt Enter your name: and read one word. ③ Prompt Enter your roll number: and read one int. ④ Print exactly three lines: a row of ten = signs · Welcome, name (Roll roll) · the same = row again.
SAMPLE RUN inputs Diya and 41 must produce:
TARGET OUTPUT — MATCH CHARACTER FOR CHARACTER
Enter your name: Diya Enter your roll number: 41 ========== Welcome, Diya (Roll 41) ==========
PLAN FIRST — LIST YOUR main() LINES IN ORDER, IN PEN, BEFORE NOTEPAD++
You read the name with next() first, then the roll with nextInt(). Keep that order. (The full story of nextLine() after nextInt() is a Class 27 topic — today, just follow the brief.)
SOLUTION SHEET · EXERCISE 1 · AFTER YOUR ATTEMPT COMPILES — OR 15 MINUTES, WHICHEVER FIRST
HelloStudent, line by line.
Locked until you've fought for it. Open, then compare structure: your line order can differ; your output cannot.
Attempted honestly? Compiler consulted at least once? Then open.
C:\Users\diya\Desktop\java-practice\lab-00> javac HelloStudent.java
C:\Users\diya\Desktop\java-practice\lab-00> java HelloStudent
Enter your name: Diya
Enter your roll number: 41
==========
Welcome, Diya (Roll 41)
==========
Line 12 glues four pieces with +. Java turns roll's int into text the moment a String joins the chain — Class 3's + rule doing exercise-1 work. ✦
EXERCISE 2 OF 3 · 20 MINUTES · 30 MARKS · YOU ALONE
Exercise 2 — SimpleCalculator.java
SquareScanner read one number and did one operation. This reads two numbers and reports five operations — including the two whose int behaviour Class 4 made you trace in ink.
PROBLEM A two-number calculator for the lab bench: read a and b, print the five arithmetic results, clearly labelled.
REQUIREMENTS ① Class named exactly SimpleCalculator. ② Prompts Enter a: and Enter b:, both read as ints. ③ Five labelled output lines: Sum, Difference, Product, Quotient, Remainder — in that order, format Label = value. ④ Use a = 17, b = 5 for your first test and check the last two lines against your Class 4 knowledge before running.
SAMPLE RUN inputs 17 and 5 must produce:
TARGET OUTPUT — PREDICT THE LAST TWO LINES IN PEN FIRST
Enter a: 17 Enter b: 5 Sum = 22 Difference = 12 Product = 85 Quotient = 3 Remainder = 2
BEFORE YOU RUN — WHY IS THE QUOTIENT 3 AND NOT 3.4? ONE SENTENCE, PEN.
SOLUTION SHEET · EXERCISE 2
SimpleCalculator, line by line.
Five printlns, one pattern — and the two "dangerous" lines are only dangerous if you expected decimals from int boxes.
Your five lines printed something? Compare now — especially the last two.
C:\Users\diya\Desktop\java-practice\lab-00> javac SimpleCalculator.java
C:\Users\diya\Desktop\java-practice\lab-00> java SimpleCalculator
Enter a: 17
Enter b: 5
Sum = 22
Difference = 12
Product = 85
Quotient = 3
Remainder = 2
Why brackets on lines 11–12 but not 13–15? Without them, + would glue "Sum = " to a first, then to b — printing 175. Only + is ambiguous like this; * / % bind tighter than the string +. ✦
Sum = 175 — that's the finding of the day.
"Sum = " + a + b runs left to right: string + 17 makes "Sum = 17", then + 5 glues "5". The brackets in ("Sum = " + (a + b)) force the arithmetic first. Write this one in your notebook; it returns in the exam.
EXERCISE 3 OF 3 · 25 MINUTES · 30 MARKS · THE ONE THAT USES EVERYTHING
Exercise 3 — PassFailChecker.java
Array + for + if/else + two counters. Every piece rehearsed: the array from Class 3, the loop-and-if from CountEvens, the two-road decision from EvenOrOdd. Now they work one shift together.
PROBLEM Six students' marks are already known. The class teacher wants each verdict printed, then a two-line summary of how many passed and failed.
REQUIREMENTS ① Class named exactly PassFailChecker. ② Start from this array — type it exactly: int[] marks = { 62, 34, 78, 40, 91, 25 }; ③ Pass mark is 40 or above. ④ For each student print Student 1: 62 - PASS style lines (numbering from 1, not 0). ⑤ Declare passCount and failCount before the loop; step the right one in each branch. ⑥ After the loop, print Passed: and Failed: lines.
SAMPLE RUN with the given array, exactly this:
TARGET OUTPUT — COUNT THE PASSES IN PEN BEFORE CODING: IS 40 A PASS?
Student 1: 62 - PASS Student 2: 34 - FAIL Student 3: 78 - PASS Student 4: 40 - PASS Student 5: 91 - PASS Student 6: 25 - FAIL Passed: 4 Failed: 2
PLAN FIRST — WHICH CONDITION MAKES 40 A PASS: > 40 OR >= 40? AND WHY DOES Student 1 PRINT marks[0]?
SOLUTION SHEET · EXERCISE 3
PassFailChecker, line by line.
Watch the two counters and the i + 1 label — the two places this exercise decides your marks.
Eight lines of output matching the target? Then this is just a victory lap.
C:\Users\diya\Desktop\java-practice\lab-00> javac PassFailChecker.java
C:\Users\diya\Desktop\java-practice\lab-00> java PassFailChecker
Student 1: 62 - PASS
Student 2: 34 - FAIL
Student 3: 78 - PASS
Student 4: 40 - PASS
Student 5: 91 - PASS
Student 6: 25 - FAIL
Passed: 4
Failed: 2
Student 4 with exactly 40 passes — because line 9 says >=, not >. One character, one student's semester. Boundaries are where marks live. ✦
LAST 10 MINUTES · DEBRIEF, MARKS & WHAT LEAVES THE ROOM WITH YOU
Six mistakes, one rubric, one folder to show.
Before you log off: the six mistakes this lab sees every single year — check yourself against each — then how the 100 marks split, and exactly what to submit.
| # | THE MISTAKE | WHAT THE MACHINE SAYS / SHOWS | THE FIX |
|---|---|---|---|
| 1 | File name ≠ class name (hellostudent.java) | class HelloStudent is public, should be declared in a file named HelloStudent.java | Match capital for capital, always |
| 2 | Compiling from the wrong folder | error: file not found | Read your prompt — it must end in lab-00> |
| 3 | java HelloStudent.java after javac | error: could not find or load main class HelloStudent.java | java HelloStudent — class name, no extension |
| 4 | = instead of == in the pass check | incompatible types: int cannot be converted to boolean | Comparison is always two characters |
| 5 | Counters declared inside the loop | Compiles… then Passed: 0 or cannot find symbol at the println | Declare before the loop — scope dies at } |
| 6 | "Sum = " + a + b without brackets | Prints Sum = 175 — no error at all, just wrong | Bracket the arithmetic: (a + b) |
Notice something about those six? Only one of them is about "not knowing Java". The other five are discipline: naming, folders, commands, scope, brackets. That is why the prelab exists — and why next lab assumes all six are behind you.
THE 100 MARKS · KNOW WHERE THEY LIVE BEFORE THE EXAMINER ASKS
| COMPONENT | MARKS | WHAT EARNS FULL MARKS |
|---|---|---|
| Prelab · 10 theory Qs in ink | 10 | All ten attempted in your ruled notebook, before lab day — checked at the door |
| Prelab · 4 programs | 10 | Four .java files in your lab-00 folder, each compiled at least once (the .class is the proof) |
| Exercise 1 · HelloStudent | 20 | Compiles · output matches the target exactly · file named right |
| Exercise 2 · SimpleCalculator | 30 | Compiles · all five lines labelled and correct · you can explain Quotient = 3 when asked |
| Exercise 3 · PassFailChecker | 30 | Compiles · all 8 lines match · counters declared before the loop · you can explain the i + 1 |
The examiner will point at one line of your own program and ask why. A working program you can't explain scores like a borrowed one — because it is one.
WHAT TO SUBMIT — YOUR FOLDER AT THE END OF THE SESSION
lab-00 folder + your ruled notebook
Folder zipped or copied as your lab instructor directs; notebook open to the ten theory answers. Both leave the room checked today — nothing is "emailed later".
Complete this sentence in your notebook: "The mistake that cost me the most time today was ______, and next lab I will ______." One honest line — it's the cheapest marks-insurance you'll ever write.
MY LAB 0 FOLDER · YOUR PROGRAMS, READY TO SUBMIT AS ONE PDF
Write each program in its own box on this page and press Compile & Run until it works. When it compiles and runs, it saves itself here with a green tick — a later working run replaces the saved copy. At the end, type your name and roll number below and press Download all programs (PDF). That PDF is what you submit.