LAB 3 · OPENER · l03-opener
Today you build the shape
every real Java project has.
Every program you have written in this course so far has been one folder, files loose inside it. Real software is never like that. Open any Java project in any company in Hyderabad and you will find a tree of folders with names like com.something.something, and code in one folder calling code in another. Today you build that shape for the first time — small, but genuinely real. And because Class 16 already taught every piece, today is mostly careful typing rather than new ideas.
UI24PC321CS · OOP THROUGH JAVA LAB · B.E. III SEM · VASAVI COLLEGE OF ENGINEERING
Lab 3 — two packages,
one attendance app.
A calculator class that knows Vasavi's 75 % detention rule, living in its own package. A driver in a different package that imports it and reports on five students. By the end of the session both packages exist as real folders on your disk, and you can point at them.
R-24 SYLLABUS · LAB PROGRAMMING EXERCISE 3 · VERBATIM
“A program to create Packages.”
What you are building, in one picture
Two packages. One does the arithmetic; the other does the talking. Read the tree before you read anything else today — every instruction in this lab is a step towards making your own screen look like this.
PACKAGE EXPLORER · HIERARCHICAL
THE TARGET · TWO SIBLING PACKAGES UNDER com.college · ONE IMPORTS THE OTHER · THE CONSOLE PROVES IT RAN
Today's four objectives
Create com.college.attendance and com.college.app in Eclipse, and open File Explorer to confirm that six actual folders now exist on your hard disk. A package you cannot point at on disk is a package you do not yet understand.
javac -d
Eclipse will build for you all session. But you will also build the same two packages once by hand, exactly as in Class 16 Part 9, so that you know what the IDE's green arrow is actually doing — and so that a broken lab machine cannot stop you.
Make Main in one package use a class in another, with import and with public. This is the objective that carries the most marks, because it is the one that proves a namespace is doing real work.
Vasavi's real rule: below 75 % attendance is detention. You will write computePercentage and isDetained and find out why 100.0 in one place decides whether your program is right or quietly, believably wrong.
How the next two hours run
TEN PARTS · IN ORDER · DO NOT SKIP TO PART 6
com.college.attendance.AttendanceCalculator, specified but not written for you
45 MARKS
com.college.app.Main, five students, cross-package
45 MARKS
LAB 3 OF 14 · 10 PARTS · 4 UNGRADED DRILLS + 2 GRADED EXERCISES · 100 MARKS · BUILT IN ECLIPSE, VERIFIED ONCE ON THE COMMAND LINE
Eclipse for everything graded. Both exercises are built, run and shown in Eclipse, in your existing eclipse-workspace folder from Lab 2. Every file path in this lab is written out in full so that you never have to guess where something landed.
One deliberate exception, in Part 9. After Exercise 2 is working in the IDE, you will rebuild the same two packages once in a terminal with javac -d . — not to make life hard, but because the IDE's green arrow hides the two commands that actually matter, and the lab external examiner is entitled to ask you what they are.
PART 2 · PRELAB THEORY · l03-prelab-theory
Five questions. Pen, notebook,
no Eclipse, no scrolling ahead.
These are the five things the evaluator may ask you in the viva, and they are also the five things that make the graded exercises easy. Write real sentences — not keywords. If you cannot answer one, write down what you do not know about it; that is a useful answer too, and Part 3 will close it.
Q1 · 2 MARKS OF VIVA What problem does a package solve?
Answer in two or three sentences, and name at least two distinct benefits. Then add one concrete example of the problem occurring — a situation where two classes with the same simple name would genuinely collide.
Q2 What exactly does import com.college.attendance.*; do — and what does it not do?
Three specific things to address: (a) does it copy any code into your file? (b) does it give you access to a class that is not public? (c) does it include a class sitting in com.college.attendance.rules?
Q3 What is the classpath, in one sentence a beginner would understand?
Then answer the practical half: in Class 16 Part 9 you ran java com.college.attendance.AttendanceCalculator and it worked, without you ever setting a classpath. Why did it work? One sentence.
Q4 What is a fully-qualified name, and when are you forced to use one?
Give the fully-qualified name of the calculator class you are about to write. Then give one situation where an import cannot help you and the fully-qualified name is the only way — you met exactly one such situation in Class 16.
Q5 · THE ONE THAT SAVES YOUR SESSION A class declares package com.college.attendance; but its file sits in the folder src\com\college\app\. What happens?
State whether it is a compile-time or a run-time problem, write the compiler message as closely as you can remember it, and give two different ways to fix it. Then say which fix you would choose if the class really is an attendance class, and why.
PART 3 · MODEL ANSWERS · l03-prelab-theory-answers
Now compare. Mark your own paper
honestly — nobody else will see it.
Read each answer against what you wrote. Where you were right, tick it and move on. Where you were vague, copy the sentence in bold into your notebook — those five bold sentences are the whole viva. Where you were wrong, do not feel bad: four of these five are the exact places students lose marks in Lab 3, which is precisely why we are doing this before Eclipse opens.
A1 · What problem does a package solve?
A package is a namespace: it gives every class a long, unique address so that two classes with the same simple name can coexist. That is the one-sentence answer. Everything else — folders, tidiness, access control — follows from it.
The real, unavoidable problem. Two different programmers, or two different libraries, both want a class called Date. Without packages, one of them simply cannot be used. With packages, both exist happily as java.util.Date and java.sql.Date.
Your calculator lives in com.college.attendance, your driver in com.college.app. Anyone opening the project can see the structure without reading a single line of code. In a 200-class project this stops being a nicety and becomes the only way to navigate.
Recall the access table from Class 16 Part 7: package-private (no modifier) and protected mean nothing at all until packages exist. Packages are what turn four access levels into four different access levels.
A jar file is a bundle of packages. Because the package name is unique worldwide, you can drop somebody else's jar onto your classpath without any fear that it will collide with your own class names.
Student for the attendance module, and the hostel office writes a class Student for room allocation. Both are legitimately called Student — renaming either one to Student2 would be absurd. Put them in com.college.attendance.Student and com.college.hostel.Student and the problem evaporates: the compiler sees two completely different types, and any file needing both simply uses the long name for at least one of them.
THE HALF-ANSWER THAT LOSES THE MARK
“A package organises classes into folders.” This is true but backwards, and an examiner hears it as memorised. The folder is not the purpose — the folder is a consequence. The purpose is the unique name; the compiler then insists the folder path mirrors that name so it can find the file on disk. Say “namespace” first, “folder” second, and you sound like someone who understands it.
A2 · What import com.college.attendance.*; does — and does not do
An import is a note to the compiler about spelling. It says: in this file, when I write a short class name, look in this package for it. It grants no access, copies no code, and costs nothing at run time.
| THE QUESTION | THE ANSWER | WHY |
|---|---|---|
| (a) Does it copy any code into my file? | NO | Nothing is copied — this is not C's #include. Your .class file does not grow by one byte. The compiler stores the fully-qualified name inside the bytecode either way, so an imported and a non-imported version of the same program compile to byte-for-byte identical output. |
(b) Does it give me access to a class that is not public? | NO | Access is decided only by public / protected / no-modifier / private. If Greeter is package-private, importing it produces The type com.college.util.Greeter is not visible — the import line compiled fine and helped you not at all. |
(c) Does it include com.college.attendance.rules.Detention? | NO | The * means “every class directly in this package”. It is not recursive. Despite the folder rules sitting inside the folder attendance, Java has no concept of a sub-package inheriting anything — com.college.attendance.rules is simply a different package with a longer name, and needs its own import line. |
import is not permission — it is abbreviation.
A3 · What is the classpath?
THE DEFINITION AN EXAMINER ACCEPTS
“The classpath is the list of starting folders (and jar files) in which the JVM and the compiler look for classes. A package name tells Java the route from a starting folder to the class file; the classpath tells Java which starting folders to try.”
Add the mechanism: “the fully-qualified name com.college.attendance.AttendanceCalculator is translated into the relative path com\college\attendance\AttendanceCalculator.class, and that path is appended to each classpath entry in turn until the file is found.”
The practical half — why Part 9 worked with no classpath set. Because there is always a classpath. If you never mention one, Java uses a default of exactly one entry: . — the folder you are currently standing in. In Class 16 Part 9 you had cd-ed into class-16, and the compiled tree began right there as com\college\attendance\. So the default entry was the correct entry, purely because of where your feet were.
.classpath, and shows it in the UI as Build Path. Every time you save, Eclipse effectively runs javac -d bin; every time you press Run, it effectively runs java -cp bin .... Same two commands, hidden behind a green triangle.
A4 · Fully-qualified names
A fully-qualified name is a class's package name followed by a dot and its simple name — its complete, globally unique address. The calculator you are about to write has the fully-qualified name com.college.attendance.AttendanceCalculator; its simple name is just AttendanceCalculator.
import. Merely long.import CANNOT SAVE YOUTHE RULE IN ONE LINE
You are forced to use a fully-qualified name in exactly one circumstance: when two classes you need in the same file have the same simple name. Every other use of a fully-qualified name is a stylistic choice — correct, but verbose.
A5 · The declaration does not match the folder
The class says package com.college.attendance; but the file sits in src\com\college\app\. The class is now making two contradictory statements about its own address — one in line 1, one by where it physically sits. Java refuses to guess which one you meant.
TWO FIXES — AND WHICH TO CHOOSE
Fix A — move the file. Keep line 1 as it is and drag the file into src\com\college\attendance\. In Eclipse: click the file, press Alt + Shift + V, choose the correct package.
Fix B — change line 1 to package com.college.app;. Also perfectly legal, and the error vanishes instantly.
If it really is an attendance class, choose Fix A. Both fixes silence the compiler, but only one keeps the code honest: the package name is documentation that the compiler happens to enforce. Fix B silences the compiler by making the documentation lie — you have filed the attendance register in the drawer marked “app”, and in six weeks nobody, including you, will find it.
COMPILE TIME OR RUN TIME? IT DEPENDS ON THE TOOL — SAY BOTH
In Eclipse it is a compile-time error, and you get it before you even press Run, because Eclipse knows the source folder is src and can therefore work out what package it expected. That is the answer the question is fishing for.
On the raw command line it usually surfaces at run time instead, which is far more confusing. javac compiles the file without complaint — it was not told where your source root is, so it has nothing to compare against — and drops the .class file wherever -d sends it. The failure then arrives as Error: Could not find or load main class, because the class is not sitting where its name promises it would be. Mention both halves and the mark is yours.
PART 4 · PRELAB CODING TASKS · l03-prelab-coding-tasks
Four drills. Four moves.
None of them graded — all of them needed.
Each drill isolates exactly one thing you will do in the graded exercises, with everything else stripped away. Drill 1 is “put a class in a package”. Drill 2 is “use it from somewhere else with an import”. Drill 3 is “use it with no import at all”. Drill 4 is “build two packages by hand, without an IDE, so you can never be mystified by one again”. Attempt each one before you unlock its sheet — ten minutes stuck is the entry ticket.
First · one project to hold all four drills
Drills 1, 2 and 3 live in Eclipse. Make one project for them now so you are not creating projects mid-drill. In Eclipse: File → New → Java Project.
Create a Java Project
Create a Java project in the workspace or in an external location.
“Create module-info.java” MUST BE LEFT UNTICKED — MODULES ARE OUT OF SCOPE FOR THIS COURSE AND A module-info.java WILL BLOCK YOUR CROSS-PACKAGE CALL WITH AN ERROR NOBODY IN THE LAB CAN EXPLAIN
Lab03Drills containing src and JRE System Library, and no module-info.java. If a module-info.java appeared, right-click it → Delete. That is the whole fix.
Create a package com.college.util and inside it a public class Greeter with a public method sayHi(). sayHi() prints a greeting and then prints the class's own fully-qualified name. Give Greeter its own main so it can be run directly.
None. No Scanner, no arguments — the whole point of the drill is the address of the class, not its behaviour.
Hi from the util packagecom.college.util.Greeter
Line 1 of the file (package com.college.util;) and the folder the file lives in (src\com\college\util\) are the same fact stated twice. Eclipse writes both for you when you name the package in the New Class dialog.
src → New → Class. In the dialog, type com.college.util into the Package field and Greeter into the Name field, tick public static void main(String[] args), press Finish. You do not create the folders yourself — naming the package is creating them.
package com.college.util;public class Greeter{ public void sayHi() { System.out.println("Hi from the util package"); System.out.println(getClass().getName()); } public static void main(String[] args) { Greeter g = new Greeter(); g.sayHi(); }}getClass().getName() asks the running object what its real name is, and the object answers with the fully-qualified name. You never typed that dotted string as text anywhere — it was assembled by the compiler from line 1 plus the class name. The package is not decoration; it is genuinely part of the class's identity. BOTH public WORDS MATTER — DO NOT DROP EITHER
public on line 3 is what lets a class in a different package see Greeter at all. public on line 5 is what lets it call sayHi(). Drop the first and Drill 2 fails with The type com.college.util.Greeter is not visible. Drop the second and it fails with The method sayHi() from the type Greeter is not visible. Right now, inside a single package, both errors are invisible — which is exactly why beginners leave them out and then cannot explain Drill 2.
Greeter.java → Properties and read the Location line, or open eclipse-workspace\Lab03Drills\src\ in File Explorer. You will find three real, nested folders: com, then college, then util. You created them by typing one dotted line into a text field. That is worth seeing once with your own eyes.
importMIRRORS EX 2 · NOT GRADEDIn the same project but outside any package (i.e. directly in src, the default package), write HelloDrill. Import com.college.util.Greeter, create one, call sayHi(), then print HelloDrill's own fully-qualified name for comparison.
None.
Hi from the util packagecom.college.util.Greeter...and I am HelloDrill
This is Exercise 2 in miniature: one class using a class that lives somewhere else. Two things had to be true for it to work — Greeter is public, and the import line names it. Neither alone is enough.
import com.college.util.Greeter;public class HelloDrill{ public static void main(String[] args) { Greeter g = new Greeter(); // short name, thanks to line 1 g.sayHi(); System.out.println("...and I am " + HelloDrill.class.getName()); }}HelloDrill is running, yet the console says com.college.util.Greeter. That is because getClass() on line 8 of Greeter.java reports the class of the object it was called on — and that object is a Greeter. The running class is irrelevant.HelloDrill's fully-qualified name has no dots at all. It is in the default package, so its package name is the empty string, and its full address is simply HelloDrill. Beginners expect src.HelloDrill or default.HelloDrill; neither exists.HelloDrill.class.getName() AND NOT getClass().getName()getClass() is an instance method — it asks “what am I?” and needs an object to be the “I”. Inside main there is no object; main is static.Cannot make a static reference to the non-static method getClass() from the type Object — the same error you met in Class 7 when you first put main and an instance method in one class.HelloDrill.class is a class literal: it hands you the class object directly, with no instance involved. Then .getName() works exactly as before. Remember it as: object → getClass(), class name → .class.THE ONE-WAY STREET — MEMORISE THIS, IT IS A CLASSIC VIVA QUESTION
A class in the default package can import from a named package — which is exactly what you just did, and it works fine.
But the reverse is impossible. A class inside com.college.util can never use HelloDrill, because there is no name you could write to refer to it: there is no package name to qualify it with, and import HelloDrill; is not valid syntax. Classes in the default package are invisible to every packaged class in the program.
This is the real, practical reason professional Java never uses the default package — and the reason Exercise 2 puts Main into com.college.app instead of leaving it loose in src.
import linesPROVES A2 & A4 · NOT GRADEDWrite FqnDrill in the default package. It must do the same job as Drill 2 — use Greeter — but the file must contain no import statement whatsoever. Use the fully-qualified name instead. Do it twice: once via a variable, once inline in a single statement.
None.
Four lines — the two-line greeting, printed twice, because two separate Greeter objects are created and each prints its own two lines.
import was never necessary, only convenient. This drill is the physical proof of A2: if importing granted access, removing it would break the program. It does not.
import, and you only get it through your fingers.
public class FqnDrill{ public static void main(String[] args) { com.college.util.Greeter g = new com.college.util.Greeter(); g.sayHi(); new com.college.util.Greeter().sayHi(); }}WHAT LINE 5 ACTUALLY TEACHES
Read it slowly: com.college.util.Greeter appears twice, once as the type and once after new. In Drill 2 the identical statement read Greeter g = new Greeter();. Both programs compile to identical bytecode, because the compiler stores the long name inside the .class file either way — exactly what A2 claimed. The short form existed only in your source text.
Line 8 is the same idea taken to its limit: an object built, used and abandoned in one statement, its class named in full. Legal, occasionally useful, and completely unremarkable once you stop reading the dots as magic.
A DOT IS NOT ALWAYS A DOT
There are two very different dots on line 5. In com.college.util.Greeter the dots are package separators — they are walking you down a folder tree. In g.sayHi() the dot is member access — it is reaching inside an object. Same character, unrelated jobs, and Java tells them apart purely by whether the thing on the left is a package name or a value. This is why com.college.util renders as one long type name, not as three variables.
Without Eclipse, build a two-package program: com.a.Foo with a method name() returning a String, and com.b.Bar holding main, importing Foo and printing both classes' messages. Create the folders yourself, compile with javac -d ., run with java com.b.Bar.
None. Everything is typed into Notepad++ and run from the Command Prompt.
Foo, from package com.aBar, from package com.b
Everything Eclipse did silently in Drills 1–3, done by your own hands: you make the folders, you write the package lines, you point javac at an output root and you hand java a dotted name. After this, no package error can mystify you.
This one drill is deliberately done outside the IDE, and Notepad++ is the right tool for it. Eclipse is genuinely excellent at packages — so excellent that it hides every single step. You have now created three package folders without ever seeing a folder being created. That is comfortable, and it is why students freeze the first time a package error appears in an exam hall or on somebody else's machine.
Notepad++ does one thing: it saves the exact characters you typed into the exact file you named. No build path, no auto-compile, no quick-fix. Every folder, every package line and every command is visibly yours. Ten minutes here permanently removes the mystery — and then you go straight back to Eclipse for everything graded.
Step 1 · Make the folders yourself
Open the Command Prompt (press Win, type cmd, press Enter) and build the tree by hand.
mkdir com\a had to create com before it could create a inside it, so it created both. The second command found com already there and only added b. You now have com\a and com\b — two sibling packages under one shared first part of their names.Step 2 · Type the two files in Notepad++
In Notepad++, File → New, type the first file, then File → Save As and navigate into the folder shown on the strip. Set the Save as type dropdown to All types (*.*) before saving, or Notepad++ may append .txt and javac will not see your file at all.
package com.a;public class Foo{ public String name() { return "Foo, from package com.a"; }}com.a.Foo, and it had better be sitting in a folder path ending com\a\ — which is why Step 1 came first.public is compulsory here. Bar lives in a different package, and a package-private Foo would be invisible to it.public again, for the same reason one level down. This class has no main: it is a library class, exactly like the AttendanceCalculator you will write in Exercise 1.public words, one address. That is the entire shape of a packaged library class.package com.b;import com.a.Foo;public class Bar{ public static void main(String[] args) { Foo f = new Foo(); System.out.println(f.name()); System.out.println("Bar, from package com.b"); }}package, and it must be first. Not first non-blank line by convention: first by the language specification. Only comments and blank lines may precede it.import, and it must come after package. Swap lines 1 and 3 and you get Syntax error on token "import", or in some versions The declared package does not match…. Both messages are unhelpful; the cause is simply the order.Foo works only because of line 3. Delete line 3 and this becomes Foo cannot be resolved to a type, and your two options are to restore the import or write com.a.Foo in full.Step 3 · Look at what you built, then compile and run it
Before compiling, confirm the tree with your own eyes. tree /f prints the folder structure including files.
tree /f.java files, each two folders deep, each in the folder its own line 1 promised. If you see Foo.java.txt here, go back to Notepad++ and re-save with All types (*.*) selected — that single dropdown is the most common Drill 4 failure.FOUR THINGS TO SAY OUT LOUD ABOUT THOSE TWO COMMANDS
1 · Why both files are named on one javac line. Bar.java line 9 uses Foo, so the compiler must be able to check Foo exists and really has a name() method returning String. Handing it both sources lets it do that in one pass. Compile Bar.java alone from a clean folder and you get package com.a does not exist.
2 · What -d . means. “Put the compiled output under this folder, creating package sub-folders as needed.” Here the output root happens to be the same folder as the sources, so Foo.class lands next to Foo.java. Eclipse uses -d bin instead, which is why its .class files live in a separate bin tree. Same flag, different destination.
3 · Why the two commands use different separators. javac was given file paths, so they use backslashes: com\a\Foo.java. java was given a class name, so it uses dots: com.b.Bar. This is the single most common command-line mistake in this lab. java com/b/Bar and java com.b.Bar.class are both rejected.
4 · Why java com.a.Foo would fail. It compiles fine and its .class file exists, but it has no main. You would get Main method not found in class com.a.Foo — a run-time complaint about a perfectly valid class. Only Bar is runnable.
What each drill was actually for
| DRILL | THE MOVE YOU PRACTISED | WHERE IT IS GRADED |
|---|---|---|
1 · com.college.util.Greeter | Declaring a package and putting a public library class in it — with public on both the class and the method. | Exercise 1 — com.college.attendance.AttendanceCalculator is the same shape with real arithmetic inside. |
2 · HelloDrill | Importing across a package boundary and calling a method on the imported class. | Exercise 2 — com.college.app.Main imports the calculator and drives five students through it. |
3 · FqnDrill | Doing the same job with fully-qualified names, proving import is convenience and not permission. | The viva — questions A2 and A4 are answered by this drill, not by memory. |
4 · com.a.Foo + com.b.Bar | Building the folder tree by hand, compiling with javac -d ., running a dotted class name. | Exercise 2's command-line rebuild — and every package error you will ever have to diagnose without an IDE. |
PART 5 · WALKTHROUGH · l03-walkthrough
The same four drills, on the projector.
Every click named out loud.
You have already attempted the drills. This screen is not new material — it is the demonstration, so you can compare your habits against the correct ones before marks are involved. Follow along on your own machine, but keep your hands still for the parts where the instruction says watch. Where your project differs from the projector, fix yours now: the graded exercises assume this exact starting state.
Stage 0 · Where we are starting from
Everyone should have Lab03Drills open, containing src, one package, and three classes. If your Package Explorer does not look like this, say so now — not in twenty minutes.
PACKAGE EXPLORER · HIERARCHICAL
THREE CLASSES, TWO PACKAGES · (default package) HOLDS THE TWO DRIVERS · com › college › util HOLDS THE LIBRARY CLASS · NO module-info.java ANYWHERE
com.college.util instead of three nested rows, use the ⋮ View Menu › Package Presentation › Hierarchical and switch, because for the rest of this lab the indentation must match the disk. (2) No red markers anywhere in the tree. (3) No module-info.java. Fix all three before Stage 1.
Stage 1 · Drill 1 rebuilt — the four clicks that create a package
I am going to delete Greeter.java and rebuild it in front of you, because the creation is the part you must be able to do without thinking. Watch first; you will repeat it in Exercise 1 in about twenty minutes.
Right-click src › New › Class
Not New › Package — watch this closely, because it surprises people. You do not need to create a package separately at all. The New Class dialog has a Package field, and typing a name into it creates the package and the class in one action. Creating a package first is legal, just an extra step.
Type com.college.util into the Package field
Type the dotted name. Do not type slashes, do not type three separate words, do not press Tab between the parts. One field, one dotted string. This single string is what will become three nested folders on disk.
Type Greeter into the Name field — with a capital G
Class names start with a capital; package names are entirely lower-case. Eclipse will warn you if you break either convention, and the warning is worth reading rather than dismissing.
Tick public static void main(String[] args), then Finish
For Drill 1 we want Greeter to be runnable on its own, so tick the box. Note for Exercise 1: you will NOT tick it there — the calculator is a library class with no main of its own, exactly like Foo in Drill 4.
Java Class
Create a new Java class.
THE Package FIELD IS THE WHOLE LESSON · ONE DOTTED STRING IN, THREE NESTED FOLDERS OUT
WATCH WHAT ECLIPSE DID THE INSTANT YOU PRESSED FINISH
It wrote line 1 for you. Look at the new editor: package com.college.util; is already there. You did not type it. Eclipse derived it from the Package field, because the declaration and the folder must agree and Eclipse refuses to let you start out disagreeing.
It created three folders on disk. src\com\, then college\ inside that, then util\ inside that. Nothing was “registered” anywhere; a package genuinely is just nested folders plus a matching line 1.
It added public to the class. Because the public radio button was selected. This is the word that makes Drill 2 possible, and the one students silently lose when they type a class by hand instead of using the dialog.
Stage 2 · Drill 2 rebuilt — and the two ways to get the import line
Now HelloDrill. Right-click src › New › Class, leave the Package field empty, name it HelloDrill, tick main, Finish. Eclipse shows a yellow warning — The use of the default package is discouraged — and it is right, but for this drill we want the default package deliberately, so that the one-way-street rule can be demonstrated.
Then, inside main, type only this and stop:
public static void main(String[] args) { Greeter g = new Greeter(); }GreetersGreeter and had no idea which class you meant. It is a naming failure, not a permission failure.import exists. Not to grant access. To resolve a name.Go to the top of the file and type import com.college.util.Greeter;. The red underline vanishes as you finish the semicolon. Do it this way at least twice today — in a written examination there is no quick-fix, and you must be able to produce this line from memory.
“Organise Imports”. Eclipse finds every unresolved name, adds the imports, and removes any that are unused. Instant and correct. Use it freely for the graded work — but only after you can write the line by hand, or you will not recognise the error when a tool is not there to fix it.
WHEN Ctrl+Shift+O ASKS YOU A QUESTION, READ IT
If two packages on the classpath both contain a class with the name you typed, Organise Imports cannot decide for you. It opens a dialog listing the candidates — the classic one being java.util.Date versus java.sql.Date — and waits.
Students click the first entry to make the dialog go away. That is how a program compiles cleanly and then behaves nothing like you expected. Read the package names and pick deliberately. The dialog appearing is not a malfunction; it is the collision problem from A1 arriving in person.
PACKAGE EXPLORER
RUN IT WITH Ctrl + F11 · THE CONSOLE OPENS AT THE BOTTOM · NOTE LINE 2 OF THE OUTPUT NAMES Greeter EVEN THOUGH HelloDrill IS THE CLASS BEING RUN
HelloDrill.java, hold Ctrl and click on the word Greeter. Eclipse jumps straight into Greeter.java, in the other package. That jump is Eclipse resolving the import for you, visibly. It is also the fastest way to check that an import points where you think it points.
Stage 3 · Drill 3 in ten seconds — deleting the import on purpose
Open FqnDrill.java. It has no import line, and it works. To make the point unmissable, watch me break and unbreak HelloDrill instead.
Greeter class changed. It is still there, still public, still compiled. Only the spelling shortcut is gone.And now the failure that is about permission
Restore the import. Then go into Greeter.java and delete the word public from line 3, so it reads class Greeter. Save. Watch HelloDrill go red.
public back before you continue. Then run HelloDrill once more and confirm you get three output lines. Your project must be in a working state before Exercise 1 begins — do not carry a red marker into graded work.
Stage 4 · Drill 4 on the projector — the terminal, once
Last stage, and the only one outside Eclipse. I will do this on the projector while you watch, because the value is in seeing the correspondence, not in racing me.
| WHAT YOU DID BY HAND IN DRILL 4 | WHAT ECLIPSE DOES FOR YOU | WHEN |
|---|---|---|
mkdir com\a | Typing com.college.util into the Package field | When you press Finish in New Class |
Typing package com.a; as line 1 | Eclipse writes line 1 itself, from the Package field | When you press Finish |
Typing import com.a.Foo; | Ctrl+Shift+O, or the quick-fix lightbulb | Whenever a name cannot be resolved |
javac -d . com\a\Foo.java com\b\Bar.java | javac -d bin on every source file in the project | Every time you press Ctrl+S |
java com.b.Bar | java -cp bin com.b.Bar | When you press Ctrl+F11 |
THE POINT OF THAT TABLE
There is no row in the right-hand column that does something the left-hand column cannot. Eclipse is not a different way of building Java programs — it is the same two commands, issued automatically, with the folders created for you.
This matters for a practical reason. When something goes wrong in Eclipse and the message makes no sense, the useful question is always: “which of those five hand-steps would have failed?” A declared package does not match error is the mkdir step and the line-1 step disagreeing. A could not find or load main class is the java step being handed a name that does not exist at that route. Once you know the manual pipeline, Eclipse stops being magic and becomes merely fast.
bin in the Package Explorer — Eclipse hides it, because it is generated output and editing it would be meaningless. Open the workspace folder in File Explorer once, as above, and you have seen it. That is enough.
Before the graded work — the four sentences
Say these out loud once. If any one of them feels unfamiliar, ask now, because from the next screen onwards marks are involved and I will stop explaining.
- A class must be
publicto be used from another package — and its methods must bepublictoo. Two separate words, two separate failures. - The folder path must mirror the
packageline exactly. In Eclipse this is automatic if you use the Package field, and broken the moment you hand-edit line 1. importgives a short name, not permission. Cannot be resolved is a naming problem; is not visible is an access problem. Different cures, in different files.- Eclipse is
javac -d binandjava -cp bin, automated. Nothing more mysterious than that is happening.
WHAT HAPPENS NEXT — AND WHAT CHANGES
Part 6 is Exercise 1, worth 45 marks. The shape is Drill 1 exactly: one public class, in one package, with public methods and no main. What is new is not the packaging — you have now done that four times — it is that the logic inside has to be right, and one of the two methods has a genuine trap in it involving integer division.
You will be given the problem statement, the input, the expected output and the one idea. No code. Write it yourself, run it, and only then unlock the solution sheet.
PART 6 · GRADED · l03-exercise-1-attendance-calculator
Exercise 1 · The calculator,
inside its own package.
Forty-five marks. The packaging is Drill 1 with different words — you have done it four times and it will take you two minutes. The logic is where the marks actually go, and one of the two methods contains a trap that has cost students marks in this lab every single year. You are given the problem, the input, the expected output and the one idea. You are not given the code. Write it, run it, and only then unlock Part 7.
Create a package com.college.attendance. Inside it, write a public class AttendanceCalculator with exactly two public methods and no main method at all:
1. computePercentage(int attended, int total) — returns a double: the attendance percentage, computed as attended * 100.0 / total.
2. isDetained(double percentage) — returns a boolean: true when the percentage is below the college minimum of 75.0, false otherwise.
None from the keyboard. No Scanner anywhere in this exercise — the two methods receive everything they need through their parameters.
The values will be supplied by Main in Exercise 2. For your own testing now, use 42 attended out of 50 and 30 attended out of 50.
This class prints nothing. It has no main, so there is nothing to run and nothing to see — that is correct and intended.
Its two methods must return: computePercentage(42, 50) must give 84.0, computePercentage(30, 50) must give 60.0, isDetained(84.0) must give false and isDetained(60.0) must give true.
A library class: it holds knowledge and answers questions, but it never decides what to do with the answers and it never talks to the screen.
That separation is the entire reason it can sit in its own package and be used by anything. Add a println to it and you have destroyed the point of the exercise.
Read this before you type — the one trap
THE PROBLEM STATEMENT SAYS 100.0, NOT 100. THAT DECIMAL POINT IS WORTH MARKS.
attended and total are both int. In Java, an arithmetic operation between two ints produces an int — the fractional part is not rounded, it is thrown away. You met this in Class 4, and this is the exercise where forgetting it becomes expensive.
So the order in which you write the multiplication and the division genuinely changes the answer, and one plausible-looking arrangement returns 0.0 for every student in the college. Before you type the method body, work out on paper what each of these produces for attended = 42, total = 50:
attended / total * 100.0attended * 100 / totalattended * 100.0 / total
Two of the three are wrong, and they are wrong in two different ways. Part 7 works all three out line by line — but do it on paper first, because the viva will ask.
System.out.println inside computePercentage to “see whether it works”, that instinct is fine but the place is wrong. return hands the number back to whoever asked; printing throws it at the screen and hands back nothing. This class must return. Testing it is Exercise 2's job — and Part 7 shows you a clean, temporary way to test it in the meantime.
Building it — the Eclipse route (this is what you submit)
Start a fresh project for the graded work. Do not build the exercises inside Lab03Drills — the evaluator needs to see a clean project containing exactly the two graded classes.
File › New › Java Project — name it Lab03
Create separate folders for sources and class files ticked. Create module-info.java unticked. Same two boxes as Part 4, same two reasons.
Right-click src › New › Class
Package field: com.college.attendance — typed dotted, in one go. Name field: AttendanceCalculator. Modifier: leave public selected.
Leave the main checkbox UNTICKED
This is the one difference from Drill 1, and it is deliberate. A library class has no main. If you tick it out of habit, delete the generated main before submitting — an empty main sitting in the calculator tells the evaluator you did not understand what you were building.
Write the two methods, then press Ctrl + S
Saving compiles. If the Problems view is empty and there are no red markers in the tree, the class is built. There is nothing to run yet.
src, then com, then college, then attendance, with AttendanceCalculator.java inside the last one. Then click into the editor and confirm line 1 reads package com.college.attendance; — written by Eclipse, not by you. If either check fails, fix it now; every later step depends on it.
The same package layout, stated as folders
Eclipse created the tree for you. Here is the identical structure written as the commands that would build it by hand — not because you must type them, but because this is the picture you should have in your head when the evaluator asks “where does this class live?”
com, college and attendance in one stroke. The second found com\college already there and added only app — the package that Exercise 2 will need.com\college\ is shared, and the two packages differ only in their last part. That is what “com.college.attendance and com.college.app are related” means physically. It is the whole argument for reverse-domain naming, visible as indentation.What the evaluator will look at — all 45 marks
No surprises. Every one of these is stated in the problem above; the list simply makes the marks visible.
- 10 MARKSThe package exists and is correct.
package com.college.attendance;as line 1, and the file physically insidesrc\com\college\attendance\. Both, agreeing. - 5 MARKSThe class is
public. Without it, Exercise 2 cannot compile at all — so this mark and the next exercise are linked. - 15 MARKS
computePercentageis correct. Right signature(int, int), right return typedouble,public, and — the fifteen marks — arithmetic that does not silently truncate. - 10 MARKS
isDetainedis correct. Takes adouble, returns aboolean,public, and uses 75.0 with a strict<. A student on exactly 75.0% is not detained — read the rule carefully. - 5 MARKSIt is a clean library class. No
main, noprintln, noScanner. It computes and returns; nothing else.
HOW TO SPEND YOUR TIME
The packaging is worth 15 of the 45 marks and takes two minutes, because Eclipse does it. The two method bodies are worth 25 and are four lines of code between them. So almost all of your remaining time should go on the three arithmetic expressions in the warning box above — work out all three on paper, decide which is right, and be ready to say why the other two fail. That single piece of reasoning is the difference between 30 and 45.
PART 7 · SOLUTION & OUTPUT · l03-exercise-1-solution-output
Exercise 1 · solved,
and the arithmetic settled for good.
Fourteen lines of code, one of which carries fifteen marks. Unlock it only after your own attempt is on screen — and then read the arithmetic section even if your version was right, because “it worked” and “I know why it worked” are different answers in a viva.
package com.college.attendance;public class AttendanceCalculator{ public double computePercentage(int attended, int total) { return attended * 100.0 / total; } public boolean isDetained(double percentage) { return percentage < 75.0; }}public is not decoration. Exercise 2's Main lives in com.college.app, a different package, and a package-private class is invisible across that boundary.public, returns double, takes two ints. Not static: the exercise says nothing about static, so Main will create an object. Either choice can be defended, but this is the plain reading of the statement.attended * 100.0 is evaluated first, and because 100.0 is a double the int is promoted, giving a double. Dividing a double by an int gives a double. No truncation can occur anywhere in the expression.double, not the raw counts. This method is deliberately ignorant of how the percentage was computed; that is what makes it reusable.boolean. There is no need for if (percentage < 75.0) { return true; } else { return false; }; it is four extra lines that say the same thing. Note < and not <=: exactly 75.0 is safe.main, no println. Nothing to run. That is what a library class looks like.attended = 42, total = 50| EXPRESSION | HOW JAVA EVALUATES IT | RESULT | VERDICT |
|---|---|---|---|
attended / total * 100.0 |
42 / 50 is int ÷ int, so it is 0 — not 0.84, not rounded to 1, simply 0. Then 0 * 100.0 is 0.0. |
0.0 |
CATASTROPHIC |
attended * 100 / total |
42 * 100 is 4200 (still int), then 4200 / 50 is int ÷ int again, giving 84. That 84 is widened to 84.0 on the way out. |
84.0 |
RIGHT BY LUCK |
attended * 100.0 / total |
42 * 100.0 promotes 42 to double and gives 4200.0. Then 4200.0 / 50 promotes 50 and gives 84.0 by real division. |
84.0 |
CORRECT |
WHY THE SECOND ONE IS THE DANGEROUS ONE — IT PASSED YOUR TEST AND IT IS STILL WRONG
attended * 100 / total gave 84.0, which is the right answer. That is precisely what makes it dangerous: it works for the test values and then quietly fails on real ones.
Change the numbers to attended = 40, total = 60. The truth is 66.66666666666667. But 40 * 100 is 4000, and 4000 / 60 is integer division, so it discards the remainder and answers 66 — printed as 66.0. Two thirds of a percent, silently deleted, with no error, no warning and no red underline.
Now go one step further, because this is the part worth saying in the viva: does that wrong number ever produce a wrong verdict? Truncation only ever makes the number smaller, and isDetained tests < 75.0. A true percentage below 75 truncates to something still below 75; a true percentage of 75 or above truncates to at least 75. So the Detained/Cleared column comes out identical either way. The bug is invisible in the verdicts and visible only in the percentages — which is exactly why it survives casual testing, and exactly why the evaluator reads line 7 rather than only the output.
THE RULE, IN A FORM YOU CAN USE UNDER PRESSURE
In any chain of arithmetic, make it floating-point as early as possible — before the first division. Once a double enters the expression, every remaining operand is promoted and nothing can be truncated after that point. Delay it and you are gambling on whether the divisions happen to come out exact.
Two other correct ways to write line 7, both accepted:
And one that looks like a fix but is not: (double) (attended / total) * 100. The cast is applied after the integer division has already thrown the fraction away, so it faithfully converts 0 into 0.0. Casting cannot recover information that has already been discarded.
Proving it works, before Exercise 2 exists
The graded class has no main, so there is nothing to press Run on — which leaves you unable to see whether your arithmetic is right. The professional answer to that is a unit test; the answer available to you today is a temporary throwaway class. Write it, run it, read the numbers, then delete it before you submit.
package com.college.attendance;public class CalcCheck{ public static void main(String[] args) { AttendanceCalculator c = new AttendanceCalculator(); System.out.println(c.computePercentage(42, 50)); System.out.println(c.computePercentage(30, 50)); System.out.println(c.computePercentage(40, 60)); System.out.println(c.isDetained(84.0)); System.out.println(c.isDetained(75.0)); System.out.println(c.isDetained(60.0)); }}Ctrl + F1166.66666666666667 means no truncation happened. If you see 66.0, line 7 of the calculator is the truncating version and you have found the bug before the evaluator did.isDetained(75.0) answers false — a student on exactly 75% is cleared. If yours says true, you wrote <= where the rule says “below 75%”, and one real student's result has just changed.CalcCheck is in com.college.attendance, the same package as the calculator, so the short name resolves with no help. Crossing a package boundary is Exercise 2's problem. DELETE CalcCheck.java BEFORE YOU SUBMIT
It is not part of the exercise. Leaving it in means your com.college.attendance package contains a stray class with a main in it, which reads as confusion about what a library package is for. Right-click it › Delete once your numbers check out. Its whole life is about ninety seconds.
Beyond the exercise — two inputs nobody tests, and what they really do
Not graded, and worth knowing, because the answers are surprising and a viva examiner who is enjoying themselves may ask. Add these two lines to CalcCheck and run it.
42 / 0 with two ints throws ArithmeticException: / by zero and stops the program. There is no int that means “infinity”, so Java has no choice but to fail.4200.0 / 0 does not throw. The IEEE 754 standard, which Java's double follows, defines a value for this: Infinity. So the method returns normally and hands back a perfectly valid double.0.0 / 0There is no sensible answer at all — not even infinity — so IEEE 754 defines NaN, “Not a Number”. Also returned normally.isDetained(Infinity) quietly answers false, and isDetained(NaN) also answers false — because every comparison involving NaN is false, including NaN < 75.0. So a subject with zero classes held would print NaN % Cleared. Nothing crashed; the report is simply nonsense.100.0 fixed the truncation bug and, as a side effect, turned a loud crash into a silent absurdity. Both behaviours are “correct” Java. A production version would reject total <= 0 before dividing — which is exactly what Class 17's exceptions are for, and why that class comes next.Mark your own Exercise 1
- 10 — Line 1 reads
package com.college.attendance;and the file sits insrc\com\college\attendance\. Check both, not one. - 5 —
public class AttendanceCalculator. - 15 —
public double computePercentage(int, int)and the expression cannot truncate. Test it with40, 60, not with42, 50. - 10 —
public boolean isDetained(double), using< 75.0. Test it with exactly75.0. - 5 — No
main, noprintln, noScannerin the graded file, andCalcCheck.javadeleted.
Lab03, do not delete anything except CalcCheck.java, and make sure the Problems view is empty before you turn the page.
PART 8 · GRADED · l03-exercise-2-main-driver
Exercise 2 · A second package,
reaching into the first.
Forty-five marks, and this is the exercise the syllabus line actually asks for. “A program to create Packages” is plural, and one package proves nothing — a single package could just be a folder you happened to make. Two packages, with one importing from the other and both compiling and running, is the smallest program that demonstrates you understand what a package is. Same rules as before: problem, input, expected output, one idea. No code.
In the same project, create a second package com.college.app. Inside it write a public class Main containing a main method.
Main must import com.college.attendance.AttendanceCalculator, create one, and use it to process five hard-coded students. For each student print the name, the percentage, and the word Detained or Cleared.
Do not modify AttendanceCalculator. It is finished.
Hard-coded in Main — no Scanner. Use exactly these five, in this order, all out of 50 classes held:
Diya Sharma 42 · Aarav Reddy 30 · Sanjana Rao 50 · Rohit Verma 37 · Meera Iyer 38
Five lines, one per student, name then percentage then verdict. For example the first must read:
Diya Sharma 84.0 % Cleared
Work out the other four yourself — and pay attention to Rohit Verma, who is the interesting one.
Two packages, one import, one working program. Main does all the deciding and all the printing; the calculator does all the computing and says nothing.
Neither class can do the job alone, and neither knows anything about the other's internals. That division of labour is the exercise.
Before you type — work the five students out on paper
You cannot check your program against an output you have not predicted. Fill this in with a pen, then run the program, then compare. All five are out of 50.
| STUDENT | ATTENDED / HELD | PERCENTAGE | VERDICT |
|---|---|---|---|
| Diya Sharma | 42 / 50 | 84.0 | Cleared — given to you as the worked example |
| Aarav Reddy | 30 / 50 | ? | ? |
| Sanjana Rao | 50 / 50 | ? | ? — what does a perfect record print? |
| Rohit Verma | 37 / 50 | ? | ? — this one is the boundary. Think carefully. |
| Meera Iyer | 38 / 50 | ? | ? — one class more than Rohit. Does that change anything? |
WHY THESE FIVE, AND NOT FIVE RANDOM NUMBERS
The five rows are chosen, not scattered. Diya is comfortably above. Aarav is comfortably below. Sanjana is the perfect case, which checks that nothing silly happens at 100. And Rohit and Meera are one single class apart, sitting either side of the 75% line — 37 out of 50 and 38 out of 50.
That pair is the whole reason your isDetained had to use < and not <=, and the whole reason the percentage had to be a real double. One attended class decides one student's academic year. If your program disagrees with your paper on Rohit or Meera, one of the two is wrong and you must find out which before you submit.
Diya Sharma 84.0 % Cleared — plain concatenation with +, spaces where you see spaces. You are not being asked to format to two decimal places, pad columns, or use printf. If you want a tidier table afterwards, do it after the five lines are correct; the marks are for the packaging and the logic, not the layout.
Building it — three clicks, then the import
Right-click src › New › Class — Package field com.college.app, Name Main
Right-click src, not the existing attendance package. Right-clicking a package pre-fills that package's name, and you would then be creating Main in the wrong place — the single commonest way this exercise goes wrong in the first thirty seconds.
This time, DO tick public static void main(String[] args)
The opposite of Exercise 1. Main is the entry point — it is the class you will press Run on. A driver has a main; a library class does not.
Write the body. When AttendanceCalculator goes red, add the import.
Type it by hand as import com.college.attendance.AttendanceCalculator; at least once today, then use Ctrl + Shift + O afterwards. In the end-semester written paper there is no quick-fix key.
PACKAGE EXPLORER · HIERARCHICAL
THIS IS THE TREE THE EVALUATOR WANTS TO SEE · com › college SHARED, THEN TWO SIBLING PACKAGES app AND attendance · TWO PACKAGES, ONE PROJECT, ONE IMPORT BETWEEN THEM
Main.java is the active editor. If Eclipse runs the wrong class, right-click Main.java › Run As › Java Application to pin it. You should get five lines and no red text.
Where the 45 marks are
- 10 MARKSThe second package is real.
package com.college.app;as line 1, file insidesrc\com\college\app\, sitting besideattendanceand not inside it. - 10 MARKSThe import works and is used.
import com.college.attendance.AttendanceCalculator;, and the class used by its short name in the body. A fully-qualified name instead is accepted but you must be able to explain the difference. - 10 MARKSAll five students are processed, in the given order, with the given numbers. Five lines out, not four, not six.
- 10 MARKSBoth methods are actually used.
computePercentagefor the number andisDetainedfor the verdict. Re-testing< 75yourself insideMainloses these marks — it means the calculator was not needed. - 5 MARKSThe verdicts are right, most importantly for Rohit and Meera.
THE TEN-MARK MISTAKE THAT STILL PRODUCES PERFECT OUTPUT
Some students compute the percentage with the calculator and then write if (pct < 75) directly inside Main, never calling isDetained at all. The output is identical and the marks are gone.
The reason is not pedantry. The 75% rule is a college policy, and it lives in exactly one place: the attendance package. If the rule changes to 80%, a correct program is fixed by editing one line in AttendanceCalculator. A program that re-tested the number inside Main now has the policy written in two places, and one of them will be forgotten. Duplicating a rule is the bug; the wrong output is only the symptom that eventually appears.
PART 9 · SOLUTION & OUTPUT · l03-exercise-2-solution-output
Exercise 2 · solved — then built
again with no IDE at all.
Two things behind this lock. First the graded solution and its real console output. Then the same two packages rebuilt from bare files in Notepad++ and the Command Prompt — because the moment you have watched javac -d and java handle a two-package program with your own eyes, packages stop being an Eclipse feature and become something you understand.
package com.college.app;import com.college.attendance.AttendanceCalculator;public class Main{ public static void main(String[] args) { AttendanceCalculator calc = new AttendanceCalculator(); String[] names = { "Diya Sharma", "Aarav Reddy", "Sanjana Rao", "Rohit Verma", "Meera Iyer" }; int[] attended = { 42, 30, 50, 37, 38 }; int held = 50;Note the braces on lines 11–13 sit inline. Those are array initialisers — they hold data, not statements, so the Allman rule does not apply to them.
Nothing has been printed yet. The next part is the loop that does the work.
for (int i = 0; i < names.length; i++) { double pct = calc.computePercentage(attended[i], held); String verdict; if (calc.isDetained(pct)) { verdict = "Detained"; } else { verdict = "Cleared"; } System.out.println(names[i] + " " + pct + " % " + verdict); } }}Ctrl + F11 ON Main.javaisDetained(75.0) in Part 7's CalcCheck — which is exactly why that throwaway class existed.com.college.attendance.*. Both compile identically; the single-class form is preferred because a reader can see at a glance exactly what this file depends on. With a * they must go looking.names[3] and attended[3] are the same student. It is the honest tool for five hard-coded rows with the material you have. Array initialisers are data, so the braces stay on the line — the Allman rule applies to code blocks, not to a list of values.heldAll five students are in the same class, so 50 is written once. Putting 50 five times inside the loop would work and would be worse — the same duplication argument as the 75% rule.pct is computed once and used twice: for the verdict on line 21 and for the printing on line 30. Calling computePercentage twice would give the same answer and do the work twice.if (calc.isDetained(pct)) — Main asks the calculator for the verdict and merely turns it into a word. The number 75 appears nowhere in this file. That is the ten-mark distinction from Part 8.READ THE TWO FILES TOGETHER — THIS IS THE ANSWER TO “WHY PACKAGES?”
AttendanceCalculator knows arithmetic and college policy. It has never heard of Diya Sharma, does not know how many students exist, and cannot print. Main knows five students and how to lay out a line of text. It does not know what the pass mark is, and it does not know how a percentage is computed.
Change the pass mark to 80% and you edit one line in one package. Add a sixth student and you edit one line in the other. Neither change can break the other file, because neither file can see inside the other. That is what a package boundary buys you, and it is the sentence to say if the evaluator asks why the program was not simply written as one class.
The same app again — no Eclipse, start to finish
Not graded, and not optional if you want to be sure you understood this lab. Everything above worked, and Eclipse did the packaging, the compiling and the classpath. This rebuild strips all three away. The same two files, typed into Notepad++, compiled and run by hand.
You have already done the small version in Drill 4 with com.a.Foo and com.b.Bar. This is the real one, with your actual graded classes. It takes about six minutes.
src. Nothing clever happened then either.Main.java.txt.
.classpath file, no green triangle. Two commands.FOUR THINGS IN THOSE TWO COMMANDS, WORTH SAYING OUT LOUD
1 · Why both files are on one javac line. Main.java line 18 calls computePercentage, so the compiler must check that the method exists and returns a double. Give it only Main.java from a clean folder and you get package com.college.attendance does not exist — a message about a package, even though the real problem is a missing source file.
2 · What -d . did. It made .class files under the current folder, recreating com\college\attendance\ and com\college\app\ as it went. Eclipse issues the same flag as -d bin, which is the only reason its class files live in a separate tree. Same flag, different destination.
3 · Backslashes for javac, dots for java. javac was handed file paths and java was handed a class name. java com/college/app/Main and java Main.class are both rejected, and this is the most common command-line error of the whole lab.
4 · Why you did not need -cp. You were standing in lab-03, and the default classpath is the current folder. The JVM turned com.college.app.Main into the route com\college\app\Main.class, appended it to ., and found the file. Had you run the same command one folder higher, it would have failed — and the fix would be java -cp lab-03 com.college.app.Main, which is precisely what Class 16's self-study part was about.
WHAT TO SUBMIT — THE ECLIPSE VERSION, NOT THIS ONE
This command-line rebuild is understanding, not a deliverable. The graded work is the Lab03 Eclipse project, as stated in Parts 6 and 8. Keep the lab-03 folder on your Desktop if you like — it is genuinely useful revision material a week before the end-semester exam, when the written paper asks you to state the commands.
Lab03 project has exactly two packages, CalcCheck.java is deleted, and running Main prints five lines with Rohit detained and Meera cleared. Part 10 is the debrief, the common mistakes with their real messages, the full rubric, and what to show the evaluator.
PART 10 · DEBRIEF · l03-common-mistakes-debrief-checkpoint
Six real errors, the rubric,
and what to show the evaluator.
Every message below is one the compiler or the JVM actually prints — nothing paraphrased, nothing invented. Read them now while your project is fresh, because in the end-semester lab exam you will meet at least one of them under time pressure, and the difference between a two-minute fix and a lost exercise is recognising the sentence.
Mistake 1 · The declaration and the folder disagree
app; its first line claims attendance.com.college.attendance. If the class really is the driver, change line 1 instead. Never “fix” it by editing whichever one is easier to reach.javac compiles the file without a word, and you only discover it when java reports Could not find or load main class. Say both halves in the viva.Mistake 2 · Two messages that look alike and mean opposite things
This pair separates the students who read error messages from the students who guess at them. Learn the two sentences and what each one is complaining about.
Fix: add
import com.college.attendance.AttendanceCalculator;, or press Ctrl+Shift+O, or write the fully-qualified name. The fix is in this file.public.Fix: add
public to line 3 of AttendanceCalculator.java. The fix is in the other file. No number of imports will help.AND A THIRD ONE IN THE SAME FAMILY
The method computePercentage(int, int) from the type AttendanceCalculator is not visible — the class is public but the method is not. Two separate words, two separate failures, and the message tells you which one by naming either a type or a method. Read the noun.
Mistake 3 · The percentage that is quietly wrong
attended / total was evaluated as int ÷ int first: it gives 0 for everybody except Sanjana, whose 50 / 50 is exactly 1.return attended * 100.0 / total;. Get the double into the expression before the division.84.0, 60.0, 100.0, 74.0, 76.0 — all five correct — because attended * 100 / total happens to divide exactly for every multiple of 50. It is still wrong, and the evaluator finds it by reading line 7, not the output. There is no console symptom to look for.Mistake 4 · Could not find or load main class
Main. Its name is com.college.app.Main, all of it. Fix: java com.college.app.Main.java takes a class name; only javac takes paths. Fix: use dots.com\ here. Fix: cd lab-03, or stay put and write java -cp lab-03 com.college.app.Main.Mistakes 5 and 6 · Two that cost marks without breaking anything
< 75 inside Main
The output is perfect and ten marks are gone. If the number 75 appears anywhere in Main.java, isDetained was not used and the college's policy now lives in two files. Check with Ctrl+F for 75 in Main.java — there should be no hits at all.
main left inside the calculator
Ticked out of habit in the New Class dialog, or CalcCheck.java never deleted. Everything runs. But a library package containing a runnable class says you did not grasp the split, and the evaluator is entitled to read it that way. Delete both before submitting.
app nested inside attendance
Created by right-clicking the attendance package instead of src. You end up with com.college.attendance.app — which compiles and runs perfectly, because a sub-package is just a different package. It is not two sibling packages, though, so it is not the exercise. Check the tree, not the console.
import written above package
Real message: Syntax error on token "import", which tells you nothing about the actual cause. The order is fixed by the language: package, then import, then class. Address first, abbreviations second, code third.
Debrief — what you can now do that you could not this morning
THE SYLLABUS LINE, CLOSED
The official exercise reads “A program to create Packages.” — plural. You did not create a package; you created two, put a library class in one and a driver in the other, made the driver reach across the boundary with a single import, and proved the whole thing works twice: once through Eclipse, once with two commands and no IDE at all.
That is the strongest possible reading of the syllabus line, and it is the version to describe if you are asked what you did in Lab 3.
- You can state what a package is for — a namespace giving every class a unique address, with folders as the consequence and not the purpose.
- You can create one in Eclipse by typing a dotted name into one field, and you know that this writes line 1 and creates the folders in the same action.
- You can create one by hand with
mkdir, apackageline,javac -dand a dottedjavaargument — and you know Eclipse is doing exactly those steps and nothing more. - You can cross a package boundary, and you know the two independent things that must be true for it: the class must be
public, and its name must be resolvable. - You can tell an access failure from a naming failure by reading the message, and you know that the two fixes live in different files.
- You can explain the classpath in one sentence, and say why your commands worked without ever setting one.
- You know why
100.0has a decimal point, and you can name a case where the wrong version passes every test you would casually run.
total of zero and it answers Infinity or NaN and carries on cheerfully, printing nonsense with total confidence. There is no way, with what you know today, to make it refuse. That gap has a name and a whole class of its own — and it is the next thing you learn.
The rubric — 100 marks
Nothing here is new. This is the two mark-lists from Parts 6 and 8, plus the viva, on one sheet.
| # | WHAT IS ASSESSED | DETAIL | MARKS |
|---|---|---|---|
| 1 | Exercise 1 · the package | package com.college.attendance; as line 1 and the file inside src\com\college\attendance\. Both checked. | 10 |
| 2 | Exercise 1 · public class | public class AttendanceCalculator. Without it Exercise 2 cannot compile. | 5 |
| 3 | Exercise 1 · computePercentage | public, returns double, takes (int, int), and the arithmetic cannot truncate. Tested with 40, 60. | 15 |
| 4 | Exercise 1 · isDetained | public, takes double, returns boolean, uses < 75.0. Exactly 75.0 must be Cleared. | 10 |
| 5 | Exercise 1 · clean library class | No main, no println, no Scanner, no leftover CalcCheck.java. | 5 |
| 6 | Exercise 2 · the second package | com.college.app beside attendance, not nested inside it. | 10 |
| 7 | Exercise 2 · the import | import com.college.attendance.AttendanceCalculator; present and the short name used in the body. | 10 |
| 8 | Exercise 2 · five students | All five, in order, with the given numbers. Five output lines. | 10 |
| 9 | Exercise 2 · both methods used | computePercentage for the number, isDetained for the verdict. No 75 anywhere in Main.java. | 10 |
| 10 | Exercise 2 · correct verdicts | Especially Rohit Verma 74.0 Detained and Meera Iyer 76.0 Cleared. | 5 |
| 11 | Viva | Two or three questions drawn from Part 2 — package purpose, what import does and does not do, classpath, fully-qualified names, the mismatch error. | 10 |
| TOTAL | Exercise 1 · 45 + Exercise 2 · 45 + Viva · 10 | 100 |
THE THIRTY MARKS THAT DO NOT DEPEND ON YOUR OUTPUT BEING RIGHT
Rows 1, 2, 6 and 7 total 35 marks, and every one of them is awarded for structure: two correct packages, a public class, and a working import. They are visible in the Package Explorer before your program is run.
So if you are short of time in the lab exam, get the two packages and the import right first, even with empty method bodies. A correctly packaged program with one arithmetic slip scores far higher than perfect logic sitting in the default package.
What to show the evaluator
The Package Explorer, in Hierarchical view
Showing Lab03 › src › com › college, with app and attendance as two siblings, one class in each, no red markers anywhere and no CalcCheck.java. This one screen carries 35 of the 100 marks.
Both files open, at line 1
AttendanceCalculator.java showing package com.college.attendance;, and Main.java showing its package line and the import beneath it. The evaluator will read line 7 of the calculator and search Main.java for the number 75 — be ready for both.
One live run of Main
Not a screenshot and not yesterday's console — press Ctrl + F11 in front of them and let the five lines appear. Rohit Verma detained on 74.0 and Meera Iyer cleared on 76.0 are the two rows they will look at.
Your notebook, open at the prelab
The five theory answers from Part 2 and the five-student table you filled in by hand before running the program. The viva is drawn from these ten marks' worth of writing, and having them in front of you turns the viva into a reading exercise.
Desktop\java-practice\lab-03 command-line version, mention it; it is not graded, but nobody has ever lost marks for having built the same thing twice.