Unit 2 home
LAB 3 · PACKAGES TWO-PACKAGE ATTENDANCE APP UI24PC321CS · LAB EX 3
LAB 3 · P 1/10PGDN NEXT POINT · PGUP BACK

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

TOOLEclipse IDESame workspace as Lab 2
GRADED WORK2 exercises100 marks total
WARM-UP5 theory + 4 drillsNot graded · do them first
YOU ALREADY KNOWAll of itClass 16 · Parts 7–11

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.

eclipse-workspace — Lab03 — Eclipse IDE
FileEditSourceRefactorNavigateSearchProjectRunWindowHelp

PACKAGE EXPLORER · HIERARCHICAL

Lab03
src
com
college
app
Main.java
attendance
AttendanceCalculator.java
JRE System Library [JavaSE-21]
Main.java AttendanceCalculator.java
1package com.college.app;
2
3import com.college.attendance.AttendanceCalculator;
4
5public class Main
6{
7 // ... five students, one verdict each
8}
CONSOLE · <terminated> Main [Java Application]
Diya Sharma 84.0 % Cleared
Aarav Reddy 60.0 % Detained

THE TARGET · TWO SIBLING PACKAGES UNDER com.college · ONE IMPORTS THE OTHER · THE CONSOLE PROVES IT RAN

Today's four objectives

1 · Build a real package layout

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.

2 · Compile with 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.

3 · Run across a package boundary

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.

4 · Get one honest piece of logic right

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

P1 · This opener — the target picture and the four objectives
P2 · Prelab theory — five questions, answered in your notebook in ink, before you touch Eclipse NOT GRADED
P3 · Model answers to those five — correct your own in a different colour NOT GRADED
P4 · Four coding drills — tiny programs that rehearse the graded moves one at a time NOT GRADED
P5 · Walkthrough — the four drills built live in Eclipse, every click named
P6 · EXERCISE 1com.college.attendance.AttendanceCalculator, specified but not written for you 45 MARKS
P7 · Exercise 1 solution and its real output — locked until you have attempted it
P8 · EXERCISE 2com.college.app.Main, five students, cross-package 45 MARKS
P9 · Exercise 2 solution, its output, and the same app built once on the command line
P10 · Common mistakes with their real compiler messages, debrief, rubric out of 100, and what to show the evaluator 10 MARKS VIVA

LAB 3 OF 14 · 10 PARTS · 4 UNGRADED DRILLS + 2 GRADED EXERCISES · 100 MARKS · BUILT IN ECLIPSE, VERIFIED ONCE ON THE COMMAND LINE

TOOL · ECLIPSE

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.

Before Part 2, one piece of housekeeping. Open Eclipse now and let it finish loading your workspace, so that it is warm when you need it. Then close it again and pick up your pen — the next part is written work, and doing it on paper first is not a ritual, it is the reason the exercises will take you twenty minutes instead of ninety.

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.

Do not read Part 3 until all five are written. The point is not the answers — they are two screens away — it is finding out, cheaply and privately, which of the five you only thought you knew. That is worth ten minutes of a two-hour lab.

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.

1 · Name collisions disappear

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.

2 · Related classes group together

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.

3 · A new access boundary appears

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.

4 · Code becomes distributable

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.

The concrete example, spelled out. Suppose the college writes a class 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 QUESTIONTHE ANSWERWHY
(a) Does it copy any code into my file?NONothing 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?NOAccess 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?NOThe * 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.
The sentence to memorise, because it answers all three at once: 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.

And in Eclipse? You have never set a classpath in Eclipse either, and you never will in this course — because Eclipse maintains it for you in a hidden file called .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.

FULLY-QUALIFIED — NO IMPORT LINE AT ALL
com.college.attendance.AttendanceCalculator c
= new com.college.attendance.AttendanceCalculator();
Always legal, always unambiguous, never needs an import. Merely long.
THE CASE WHERE import CANNOT SAVE YOU
import java.util.Date;
import java.sql.Date; // both want the name "Date"
Real message: The import java.sql.Date collides with another import statement. One short name cannot mean two things, so at least one of the two must be written fully-qualified in the body. That is the situation you met in Class 16 Part 10.

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

ECLIPSE · PROBLEMS VIEW · RED MARKER ON LINE 1
The declared package "com.college.attendance" does not match the expected package "com.college.app"
Read the two words. “Declared” = what line 1 of your file says. “Expected” = what the folder the file is sitting in implies. The message is not accusing either one of being wrong — it is reporting that they disagree.

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.

Forward. Five answers down, and every one of them will be tested by your fingers in the next screen. Part 4 gives you four small drills — none graded, all four mirroring one exact move you will need in the graded exercises. Do not skip them because they look trivial; they look trivial precisely because they have been stripped down to the one idea each.

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.

New Java Project

Create a Java Project

Create a Java project in the workspace or in an external location.

Lab03Drills
C:\Users\student\eclipse-workspace\Lab03Drills
Use an execution environment JRE: JavaSE-17
Create separate folders for sources and class files
Create module-info.java file
CancelFinish
TWO BOXES DECIDE YOUR WHOLE LAB · “Create separate folders for sources and class files” MUST BE TICKED — IT IS WHAT GIVES YOU src\ AND bin\, I.E. THE javac -d bin BEHAVIOUR
“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
Verify before continuing. In the Package Explorer you should see 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.
DRILL 1Put a class inside a packageMIRRORS EX 1 · NOT GRADED
PROBLEM

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.

INPUT

None. No Scanner, no arguments — the whole point of the drill is the address of the class, not its behaviour.

EXPECTED OUTPUT

Hi from the util package
com.college.util.Greeter

THE ONE IDEA

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.

How to make the package in Eclipse: right-click srcNew → 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.
only after your attempt — stuck 10 min is the ticket in
DRILL 1 · SOLVED — ONE CLASS, ONE PACKAGE, ONE HONEST ADDRESS
ECLIPSE SAVES IT AS eclipse-workspace\Lab03Drills\src\com\college\util\Greeter.java
Greeter.java
1package com.college.util;
2
3public class Greeter
4{
5 public void sayHi()
6 {
7 System.out.println("Hi from the util package");
8 System.out.println(getClass().getName());
9 }
10
11 public static void main(String[] args)
12 {
13 Greeter g = new Greeter();
14 g.sayHi();
15 }
16}
ECLIPSE CONSOLE
<terminated> Greeter [Java Application]
Hi from the util package
com.college.util.Greeter
Line 8 is the proof. 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.

Go and look at the disk. Right-click Greeter.javaProperties 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.
DRILL 2Reach into that package with importMIRRORS EX 2 · NOT GRADED
PROBLEM

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

INPUT

None.

EXPECTED OUTPUT

Hi from the util package
com.college.util.Greeter
...and I am HelloDrill

THE ONE IDEA

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.

Predict before you run. Write down, on paper, what you think line 3 of the output will be. Almost everybody gets it wrong the first time, and getting it wrong here is worth more than getting it right.
did you write your prediction down? then go ahead
DRILL 2 · SOLVED — ONE IMPORT LINE, ONE PACKAGE BOUNDARY CROSSED
ECLIPSE SAVES IT AS eclipse-workspace\Lab03Drills\src\HelloDrill.java  — no package folders, because there is no package line
HelloDrill.java
1import com.college.util.Greeter;
2
3public class HelloDrill
4{
5 public static void main(String[] args)
6 {
7 Greeter g = new Greeter(); // short name, thanks to line 1
8 g.sayHi();
9 System.out.println("...and I am " + HelloDrill.class.getName());
10 }
11}
ECLIPSE CONSOLE
<terminated> HelloDrill [Java Application]
Hi from the util package
com.college.util.Greeter
...and I am HelloDrill
Line 2 of the output is the one that catches people. 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.
Line 3 is the other one. 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.
WHY LINE 9 SAYS HelloDrill.class.getName() AND NOT getClass().getName()
THE PROBLEMgetClass() 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.
THE ERROR IF YOU TRYCannot 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.
THE FIX USED HEREHelloDrill.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.

DRILL 3The same call, with zero import linesPROVES A2 & A4 · NOT GRADED
PROBLEM

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

INPUT

None.

EXPECTED OUTPUT

Four lines — the two-line greeting, printed twice, because two separate Greeter objects are created and each prints its own two lines.

THE ONE IDEA

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.

Do not copy Drill 2 and delete line 1. Type this one from scratch. The point is to feel how long the fully-qualified name is — that feeling is the entire argument for import, and you only get it through your fingers.
typed it out in full? good — that was the drill
DRILL 3 · SOLVED — NO IMPORT, SAME RESULT
ECLIPSE SAVES IT AS eclipse-workspace\Lab03Drills\src\FqnDrill.java
FqnDrill.java — COUNT THE IMPORT LINES: ZERO
1public class FqnDrill
2{
3 public static void main(String[] args)
4 {
5 com.college.util.Greeter g = new com.college.util.Greeter();
6 g.sayHi();
7
8 new com.college.util.Greeter().sayHi();
9 }
10}
ECLIPSE CONSOLE
<terminated> FqnDrill [Java Application]
Hi from the util package
com.college.util.Greeter
Hi from the util package
com.college.util.Greeter
Four lines, because lines 5 and 8 each built a separate object and each object printed its own two lines. Nothing was imported, nothing was configured, and nothing failed.

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.

DRILL 4Two packages, built entirely by handNO IDE · NOT GRADED · THE IMPORTANT ONE
PROBLEM

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.

INPUT

None. Everything is typed into Notepad++ and run from the Command Prompt.

EXPECTED OUTPUT

Foo, from package com.a
Bar, from package com.b

THE ONE IDEA

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.

TOOL · NOTEPAD++

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.

COMMAND PROMPT — BUILDING THE PACKAGE FOLDERS
C:\Users\student> cd Desktop\java-practice
C:\...\java-practice> mkdir lab-03-drills
C:\...\java-practice> cd lab-03-drills
C:\...\lab-03-drills> mkdir com\a
C:\...\lab-03-drills> mkdir com\b
Two commands, three folders. The first 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.

SAVE THIS FILE AS Desktop\java-practice\lab-03-drills\com\a\Foo.java
Notepad++ — Foo.java
1package com.a;
2
3public class Foo
4{
5 public String name()
6 {
7 return "Foo, from package com.a";
8 }
9}
WHAT EACH LINE IS FOR
Line 1 is the address claim. From this moment the class's real name is com.a.Foo, and it had better be sitting in a folder path ending com\a\ — which is why Step 1 came first.
Line 3public is compulsory here. Bar lives in a different package, and a package-private Foo would be invisible to it.
Line 5public 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.
Nine lines, two public words, one address. That is the entire shape of a packaged library class.
SAVE THIS FILE AS Desktop\java-practice\lab-03-drills\com\b\Bar.java
Notepad++ — Bar.java
1package com.b;
2
3import com.a.Foo;
4
5public class Bar
6{
7 public static void main(String[] args)
8 {
9 Foo f = new Foo();
10 System.out.println(f.name());
11 System.out.println("Bar, from package com.b");
12 }
13}
THE ORDER OF THE FIRST THREE LINES IS FIXED BY LAW
Line 1 — 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.
Line 3 — 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.
Line 9 — the short name 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.
The mnemonic: package, import, class — address, abbreviations, then code. Never any other order.

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.

COMMAND PROMPT — tree /f
C:\...\lab-03-drills> tree /f
Folder PATH listing for volume Windows
Volume serial number is 8C4A-91D2
C:\USERS\STUDENT\DESKTOP\JAVA-PRACTICE\LAB-03-DRILLS
└───com
    ├───a
    │       Foo.java
    └───b
           Bar.java
Two .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.
COMMAND PROMPT — COMPILE, THEN RUN
C:\...\lab-03-drills> javac -d . com\a\Foo.java com\b\Bar.java
(no output — javac says nothing when it succeeds)
C:\...\lab-03-drills> java com.b.Bar
Foo, from package com.a
Bar, from package com.b
You just did, by hand, exactly what Eclipse does on every save and every Run. Nothing was configured. The only reason it worked is that the folders matched the package lines and you were standing in the right folder.

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.

a
Desktop › java-practice › lab-03-drills › com › a
Foo.java
Foo.class
THE PROOF ON DISK · Foo.class APPEARED BESIDE Foo.java BECAUSE -d . USED THIS FOLDER AS ITS OUTPUT ROOT AND THEN FOLLOWED THE ROUTE com\a\ — THE SAME ROUTE THE PACKAGE LINE NAMED

What each drill was actually for

DRILLTHE MOVE YOU PRACTISEDWHERE IT IS GRADED
1 · com.college.util.GreeterDeclaring a package and putting a public library class in it — with public on both the class and the method.Exercise 1com.college.attendance.AttendanceCalculator is the same shape with real arithmetic inside.
2 · HelloDrillImporting across a package boundary and calling a method on the imported class.Exercise 2com.college.app.Main imports the calculator and drives five students through it.
3 · FqnDrillDoing 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.BarBuilding 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.
Forward. If all four ran, you have already performed every single technical step the graded exercises need — on toy classes, with no marks at stake. What remains is real logic and real care. Part 5 is the walkthrough: the tutor rebuilds these same four drills live in Eclipse, naming every click, so you can check your habits against the demonstration before the graded work begins.

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.

eclipse-workspace — Lab03Drills — Eclipse IDE
FileEditSourceRefactorNavigateSearchProjectRunWindowHelp

PACKAGE EXPLORER · HIERARCHICAL

Lab03Drills
src
(default package)
FqnDrill.java
HelloDrill.java
com
college
util
Greeter.java
JRE System Library [JavaSE-17]
Greeter.java HelloDrill.java FqnDrill.java
package com.college.util;
public class Greeter
{
public void sayHi()
{
System.out.println("Hi from the util package");

THREE CLASSES, TWO PACKAGES · (default package) HOLDS THE TWO DRIVERS · com › college › util HOLDS THE LIBRARY CLASS · NO module-info.java ANYWHERE

Three things to check on your own screen right now. (1) The tree is in Hierarchical presentation — if you see one flat row reading 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.

1

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.

2

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.

3

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.

4

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.

New Java Class

Java Class

Create a new Java class.

Lab03Drills/src
com.college.util
Greeter
● public   ○ package-private   ○ private   ○ protected
public static void main(String[] args)
Constructors from superclass
Inherited abstract methods
CancelFinish
THE public RADIO BUTTON IS ALREADY SELECTED — LEAVE IT · IT IS WHAT LETS HelloDrill SEE THIS CLASS FROM OUTSIDE THE PACKAGE
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 srcNew › 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:

HelloDrill.java — TYPE THIS MUCH, THEN STOP
5 public static void main(String[] args)
6 {
7 Greeter g = new Greeter();
8 }
ECLIPSE · RED UNDERLINE UNDER BOTH Greeters
Greeter cannot be resolved to a type
Read the message precisely. It does not say “not visible”, and it does not say “does not exist”. It says cannot be resolved — meaning the compiler read the short word Greeter and had no idea which class you meant. It is a naming failure, not a permission failure.
And this is the whole reason import exists. Not to grant access. To resolve a name.
Way 1 · Type the import yourself

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.

Way 2 · Ctrl + Shift + O

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

eclipse-workspace — Lab03Drills/src/HelloDrill.java — Eclipse IDE
FileEditSourceRefactorNavigateSearchProjectRunWindowHelp

PACKAGE EXPLORER

Lab03Drills
src
(default package)
HelloDrill.java
com
college
util
HelloDrill.java
import com.college.util.Greeter;
public class HelloDrill
{
public static void main(String[] args)
{
Greeter g = new Greeter();
<terminated> HelloDrill [Java Application] C:\Program Files\Java\jdk-17\bin\javaw.exe
Hi from the util package
com.college.util.Greeter
...and I am HelloDrill

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

One thing to try while I talk. Click into 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.

DELETE LINE 1 — TWO RED UNDERLINES APPEAR
// import line deleted
public class HelloDrill
{
public static void main(String[] args)
{
Greeter g = new Greeter();
Greeter cannot be resolved to a type, twice. Note carefully: nothing about the Greeter class changed. It is still there, still public, still compiled. Only the spelling shortcut is gone.
FIX IT WITHOUT RESTORING THE IMPORT
// still no import line
public class HelloDrill
{
public static void main(String[] args)
{
com.college.util.Greeter g
= new com.college.util.Greeter();
Compiles, runs, produces identical output. That is A2 demonstrated rather than asserted: the import was convenience. Access was never in question.

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.

ECLIPSE · PROBLEMS VIEW — A COMPLETELY DIFFERENT MESSAGE
The type com.college.util.Greeter is not visible
Compare the two messages word by word — this is the most useful thirty seconds of the walkthrough.
cannot be resolved to a type = “I do not know which class you mean.” The cure is a name: add an import, or write the fully-qualified name.
is not visible = “I know exactly which class you mean, and you are not allowed to touch it.” The cure is an access modifier, in the other file. Adding imports here will do nothing at all, no matter how many you add.
Notice that the import line itself never went red. It resolved perfectly — it found the class. It simply has no authority to let you use it.
Put the 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 4WHAT ECLIPSE DOES FOR YOUWHEN
mkdir com\aTyping com.college.util into the Package fieldWhen you press Finish in New Class
Typing package com.a; as line 1Eclipse writes line 1 itself, from the Package fieldWhen you press Finish
Typing import com.a.Foo;Ctrl+Shift+O, or the quick-fix lightbulbWhenever a name cannot be resolved
javac -d . com\a\Foo.java com\b\Bar.javajavac -d bin on every source file in the projectEvery time you press Ctrl+S
java com.b.Barjava -cp bin com.b.BarWhen 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.

WHERE ECLIPSE PUT YOUR COMPILED CLASSES ALL ALONG eclipse-workspace\Lab03Drills\bin\com\college\util\Greeter.class
Lab03Drills
Users › student › eclipse-workspace › Lab03Drills
bin
com
college
util
Greeter.class
src
com
college
util
Greeter.java
TWO IDENTICAL PACKAGE TREES · ONE UNDER src HOLDING YOUR .java FILES, ONE UNDER bin HOLDING THE .class FILES · THIS IS THE VISIBLE RESULT OF javac -d bin, AND THE REASON bin IS THE ONLY CLASSPATH ENTRY java EVER NEEDS
You will never see 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 public to be used from another package — and its methods must be public too. Two separate words, two separate failures.
  • The folder path must mirror the package line exactly. In Eclipse this is automatic if you use the Package field, and broken the moment you hand-edit line 1.
  • import gives 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 bin and java -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.

EXERCISE 1com.college.attendance.AttendanceCalculator45 MARKS · GRADED
PROBLEM

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.

INPUT

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.

EXPECTED OUTPUT

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.

THE ONE IDEA

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.0
  • attended * 100 / total
  • attended * 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.

A returned value is not a printed value. If you find yourself wanting to write 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.

1

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.

2

Right-click src › New › Class

Package field: com.college.attendance — typed dotted, in one go. Name field: AttendanceCalculator. Modifier: leave public selected.

3

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.

4

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.

ECLIPSE SAVES IT AS eclipse-workspace\Lab03\src\com\college\attendance\AttendanceCalculator.java
Verify the package before you write a single method. Switch the Package Explorer to Hierarchical and confirm you see four nested rows: 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?”

THE LAYOUT, AS THE COMMANDS THAT WOULD CREATE IT
C:\Users\student> cd Desktop\java-practice
C:\...\java-practice> mkdir Lab03
C:\...\java-practice> cd Lab03
C:\...\Lab03> mkdir com\college\attendance
C:\...\Lab03> mkdir com\college\app
Two commands, five folders. The first built 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.
Read the shape: 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.
attendance
Users › student › eclipse-workspace › Lab03 › src › com › college › attendance
AttendanceCalculator.java
FOUR FOLDERS DEEP, AND EVERY ONE OF THEM NAMED BY LINE 1 OF THE FILE INSIDE IT · com → college → attendance · THIS PATH IS NOT A SUGGESTION — IT IS THE ROUTE java WILL FOLLOW TO FIND THE CLASS

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 inside src\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 MARKScomputePercentage is correct. Right signature (int, int), right return type double, public, and — the fifteen marks — arithmetic that does not silently truncate.
  • 10 MARKSisDetained is correct. Takes a double, returns a boolean, 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, no println, no Scanner. 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.

Attempt it now. Close this screen, build the class, and satisfy yourself that it is right. Part 7 has the full solution, the real output, and all three arithmetic expressions evaluated side by side — but it is worth nothing to you until you have your own version on screen.

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.

your own version on screen first — that is the deal
EXERCISE 1 · SOLVED — A LIBRARY CLASS IN ITS OWN PACKAGE
ECLIPSE SAVES IT AS eclipse-workspace\Lab03\src\com\college\attendance\AttendanceCalculator.java
AttendanceCalculator.java — THE COMPLETE GRADED FILE
1package com.college.attendance;
2
3public class AttendanceCalculator
4{
5 public double computePercentage(int attended, int total)
6 {
7 return attended * 100.0 / total;
8 }
9
10 public boolean isDetained(double percentage)
11 {
12 return percentage < 75.0;
13 }
14}
LINE BY LINE
Line 1 — the address. Written by Eclipse when you typed the Package field. It must be the first statement in the file.
Line 3public 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.
Line 5public, 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.
Line 7 — the fifteen-mark line. 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.
Line 10 — takes the percentage as a double, not the raw counts. This method is deliberately ignorant of how the percentage was computed; that is what makes it reusable.
Line 12 — a comparison is a 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.
Fourteen lines, no main, no println. Nothing to run. That is what a library class looks like.
THE THREE EXPRESSIONS, EVALUATED FOR attended = 42, total = 50
EXPRESSIONHOW JAVA EVALUATES ITRESULTVERDICT
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:

return (double) attended / total * 100; // explicit cast, promoted before the divide
return attended * 100d / total; // 100d is the same double as 100.0

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.

TEMPORARY — SAME PACKAGE, DELETE BEFORE SUBMITTING eclipse-workspace\Lab03\src\com\college\attendance\CalcCheck.java
CalcCheck.java — SCAFFOLDING, NOT A DELIVERABLE
1package com.college.attendance;
2
3public class CalcCheck
4{
5 public static void main(String[] args)
6 {
7 AttendanceCalculator c = new AttendanceCalculator();
8
9 System.out.println(c.computePercentage(42, 50));
10 System.out.println(c.computePercentage(30, 50));
11 System.out.println(c.computePercentage(40, 60));
12
13 System.out.println(c.isDetained(84.0));
14 System.out.println(c.isDetained(75.0));
15 System.out.println(c.isDetained(60.0));
16 }
17}
ECLIPSE CONSOLE — Ctrl + F11
<terminated> CalcCheck [Java Application]
84.0
60.0
66.66666666666667
false
false
true
Line 3 of the output is the one that proves your arithmetic. 66.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.
Line 5 checks the boundary. 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.
No imports were needed anywhere in this file. 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.

ECLIPSE CONSOLE — THE AWKWARD INPUTS
System.out.println(c.computePercentage(42, 0));
Infinity
System.out.println(c.computePercentage(0, 0));
NaN
No exception. No crash. The program keeps running. That is the part that surprises everybody.
WHY DIVIDING BY ZERO DID NOT THROW
INTEGER DIVISION42 / 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.
FLOATING-POINT DIVISION4200.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.
AND 0.0 / 0There is no sensible answer at all — not even infinity — so IEEE 754 defines NaN, “Not a Number”. Also returned normally.
THE CONSEQUENCEisDetained(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.
THE LESSONYour 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.
This is not a defect in your exercise. The problem statement fixes the formula, and you must implement the formula given. Knowing what it does at the edges is what separates someone who typed the answer from someone who understands it.

Mark your own Exercise 1

  • 10 — Line 1 reads package com.college.attendance; and the file sits in src\com\college\attendance\. Check both, not one.
  • 5public class AttendanceCalculator.
  • 15public double computePercentage(int, int) and the expression cannot truncate. Test it with 40, 60, not with 42, 50.
  • 10public boolean isDetained(double), using < 75.0. Test it with exactly 75.0.
  • 5 — No main, no println, no Scanner in the graded file, and CalcCheck.java deleted.
Leave the project open. Exercise 2 adds a second package beside this one and reaches into it. Do not close 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.

EXERCISE 2com.college.app.Main45 MARKS · GRADED
PROBLEM

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.

INPUT

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

EXPECTED OUTPUT

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.

THE ONE IDEA

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.

STUDENTATTENDED / HELDPERCENTAGEVERDICT
Diya Sharma42 / 5084.0Cleared — given to you as the worked example
Aarav Reddy30 / 50??
Sanjana Rao50 / 50?? — what does a perfect record print?
Rohit Verma37 / 50?? — this one is the boundary. Think carefully.
Meera Iyer38 / 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.

A hint about the printing, since it is not the point of the exercise. The expected line is 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

1

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.

2

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.

3

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.

ECLIPSE SAVES IT AS eclipse-workspace\Lab03\src\com\college\app\Main.java
eclipse-workspace — Lab03 — Eclipse IDE
FileEditSourceRefactorNavigateSearchProjectRunWindowHelp

PACKAGE EXPLORER · HIERARCHICAL

Lab03
src
com
college
app
Main.java
attendance
AttendanceCalculator.java
JRE System Library [JavaSE-17]
Main.java AttendanceCalculator.java
package com.college.app;
import com.college.attendance.AttendanceCalculator;
public class Main
{
// your five students go here

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

Run it with Ctrl + F11 while Main.java is the active editor. If Eclipse runs the wrong class, right-click Main.javaRun 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 inside src\com\college\app\, sitting beside attendance and 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. computePercentage for the number and isDetained for the verdict. Re-testing < 75 yourself inside Main loses 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.

Attempt it now. Five students, one import, ten or so lines. When your five lines match your paper, unlock Part 9 — which has the full solution, the real console, and the same program rebuilt from scratch on the command line, so you can see the two packages compiled and run with no IDE anywhere.

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.

five lines of your own output first
EXERCISE 2 · SOLVED — TWO PACKAGES, ONE IMPORT, ONE RUNNING APP
ECLIPSE SAVES IT AS eclipse-workspace\Lab03\src\com\college\app\Main.java
Main.java · PART 1 OF 2 — PACKAGE, IMPORT, DATA (lines 1–14)
1package com.college.app;
2
3import com.college.attendance.AttendanceCalculator;
4
5public class Main
6{
7 public static void main(String[] args)
8 {
9 AttendanceCalculator calc = new AttendanceCalculator();
10
11 String[] names = { "Diya Sharma", "Aarav Reddy", "Sanjana Rao",
12 "Rohit Verma", "Meera Iyer" };
13 int[] attended = { 42, 30, 50, 37, 38 };
14 int held = 50;
Four things done, in the only order that works. Line 1 declares which package this file belongs to. Line 3 imports the one class you need from the other package. Line 9 builds the calculator. Lines 11–14 lay out the five students' data.

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.
Main.java · PART 2 OF 2 — THE LOOP (lines 16–33)
16 for (int i = 0; i < names.length; i++)
17 {
18 double pct = calc.computePercentage(attended[i], held);
19 String verdict;
20
21 if (calc.isDetained(pct))
22 {
23 verdict = "Detained";
24 }
25 else
26 {
27 verdict = "Cleared";
28 }
29
30 System.out.println(names[i] + " " + pct + " % " + verdict);
31 }
32 }
33}
ECLIPSE CONSOLE — Ctrl + F11 ON Main.java
<terminated> Main [Java Application] C:\Program Files\Java\jdk-17\bin\javaw.exe
Diya Sharma 84.0 % Cleared
Aarav Reddy 60.0 % Detained
Sanjana Rao 100.0 % Cleared
Rohit Verma 74.0 % Detained
Meera Iyer 76.0 % Cleared
Rohit and Meera are the whole point. 37 out of 50 is 74.0 — one mark under the line, and detained. 38 out of 50 is 76.0 — cleared. One attended class, one entire academic year. If your program disagreed with your paper here, you have just found out something worth more than the five marks.
Note there is no 75.0 row in this data, because 75% of 50 is 37.5 and you cannot attend half a class. The boundary case had to be tested directly with isDetained(75.0) in Part 7's CalcCheck — which is exactly why that throwaway class existed.
FIVE DECISIONS IN THAT FILE, AND WHY EACH ONE WAS MADE
LINE 3 · THE IMPORTNames one class, not 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.
LINES 11–13 · PARALLEL ARRAYSTwo arrays whose positions line up: 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.
LINE 14 · ONE 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.
LINE 18 · STORE, THEN REUSEpct 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.
LINE 21 · ASK, DO NOT DECIDEif (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

TOOL · NOTEPAD++

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.

STEP 1 — BUILD THE TWO PACKAGE FOLDERS BY HAND
C:\Users\student> cd Desktop\java-practice
C:\...\java-practice> mkdir lab-03
C:\...\java-practice> cd lab-03
C:\...\lab-03> mkdir com\college\attendance
C:\...\lab-03> mkdir com\college\app
Exactly the tree Eclipse made for you under src. Nothing clever happened then either.
SAVE THIS FILE AS Desktop\java-practice\lab-03\com\college\attendance\AttendanceCalculator.java
AND THIS ONE AS Desktop\java-practice\lab-03\com\college\app\Main.java
The file contents are identical to the two solutions above — character for character, including line 1 of each. Copy them from your Eclipse editors if you like; the point of this exercise is the folders and the two commands, not retyping the bodies. Remember the Save as type: All types (*.*) dropdown, or you will end up with Main.java.txt.
STEP 2 — COMPILE BOTH PACKAGES, THEN RUN
C:\...\lab-03> javac -d . com\college\attendance\AttendanceCalculator.java com\college\app\Main.java
(no output — javac says nothing when it succeeds)
C:\...\lab-03> java com.college.app.Main
Diya Sharma 84.0 % Cleared
Aarav Reddy 60.0 % Detained
Sanjana Rao 100.0 % Cleared
Rohit Verma 74.0 % Detained
Meera Iyer 76.0 % Cleared
Byte for byte the same five lines Eclipse printed. No project, no build path, no .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.

lab-03
Desktop › java-practice › lab-03 › com › college
app
Main.java
Main.class
attendance
AttendanceCalculator.java
AttendanceCalculator.class
-d . PUT EACH .class FILE NEXT TO ITS OWN SOURCE, BECAUSE THE OUTPUT ROOT AND THE SOURCE ROOT WERE THE SAME FOLDER · TWO SIBLING PACKAGE FOLDERS UNDER ONE SHARED com\college\ — THE REVERSE-DOMAIN TREE, VISIBLE

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.

Both exercises are now complete. Before Part 10, confirm three things in Eclipse: the 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

ECLIPSE · RED MARKER ON LINE 1
The declared package "com.college.attendance" does not match the expected package "com.college.app"
Cause. Almost always this: you right-clicked the wrong package when creating the class, then hand-edited line 1 to say what you meant instead of moving the file. The file is in app; its first line claims attendance.
Fix. Decide which one is the truth. If the class really is the calculator, keep line 1 and move the file: click it, press Alt + Shift + V, pick 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.
On the command line this same fault is silent. 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.

A NAMING PROBLEM
AttendanceCalculator cannot be
resolved to a type
Meaning: “I do not know which class you mean.” The import line is missing, misspelt, or points at the wrong package.

Fix: add import com.college.attendance.AttendanceCalculator;, or press Ctrl+Shift+O, or write the fully-qualified name. The fix is in this file.
AN ACCESS PROBLEM
The type com.college.attendance.
AttendanceCalculator is not visible
Meaning: “I know exactly which class you mean, and you are not allowed to touch it.” The class is missing the word 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

NO ERROR AT ALL — JUST WRONG NUMBERS
Diya Sharma 0.0 % Detained
Aarav Reddy 0.0 % Detained
Sanjana Rao 100.0 % Cleared
Diagnosis by inspection. Everyone is on 0.0 except the one student with a perfect record — who comes out at 100.0. That signature means attended / total was evaluated as int ÷ int first: it gives 0 for everybody except Sanjana, whose 50 / 50 is exactly 1.
Fix. Line 7 of the calculator: return attended * 100.0 / total;. Get the double into the expression before the division.
The quieter version of the same bug prints 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

COMMAND PROMPT — THE THREE WAYS TO EARN THIS
C:\...\lab-03> java Main
Error: Could not find or load main class Main
Cause A — the short name. There is no class called Main. Its name is com.college.app.Main, all of it. Fix: java com.college.app.Main.
C:\...\lab-03> java com/college/app/Main
Error: Could not find or load main class com.college.app.Main
Cause B — slashes. Amusingly, Java converts the slashes to dots and then reports the dotted name, so the message looks like it should have worked. java takes a class name; only javac takes paths. Fix: use dots.
C:\...\java-practice> java com.college.app.Main
Error: Could not find or load main class com.college.app.Main
Cause C — standing in the wrong folder. The command is perfect; you are one level too high. The default classpath is the current folder, and there is no com\ here. Fix: cd lab-03, or stay put and write java -cp lab-03 com.college.app.Main.
All three print the same sentence, which is why this error frightens people. It is never about the class being broken — it is always about the route: wrong name, wrong separator, or wrong starting folder.

Mistakes 5 and 6 · Two that cost marks without breaking anything

5 · Testing < 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.

6 · A 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.

Bonus · 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.

Bonus · 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, a package line, javac -d and a dotted java argument — 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.0 has a decimal point, and you can name a case where the wrong version passes every test you would casually run.
The one thing this lab could not give you. Both graded classes assume the inputs are sensible. Hand the calculator a 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 ASSESSEDDETAILMARKS
1Exercise 1 · the packagepackage com.college.attendance; as line 1 and the file inside src\com\college\attendance\. Both checked.10
2Exercise 1 · public classpublic class AttendanceCalculator. Without it Exercise 2 cannot compile.5
3Exercise 1 · computePercentagepublic, returns double, takes (int, int), and the arithmetic cannot truncate. Tested with 40, 60.15
4Exercise 1 · isDetainedpublic, takes double, returns boolean, uses < 75.0. Exactly 75.0 must be Cleared.10
5Exercise 1 · clean library classNo main, no println, no Scanner, no leftover CalcCheck.java.5
6Exercise 2 · the second packagecom.college.app beside attendance, not nested inside it.10
7Exercise 2 · the importimport com.college.attendance.AttendanceCalculator; present and the short name used in the body.10
8Exercise 2 · five studentsAll five, in order, with the given numbers. Five output lines.10
9Exercise 2 · both methods usedcomputePercentage for the number, isDetained for the verdict. No 75 anywhere in Main.java.10
10Exercise 2 · correct verdictsEspecially Rohit Verma 74.0 Detained and Meera Iyer 76.0 Cleared.5
11VivaTwo or three questions drawn from Part 2 — package purpose, what import does and does not do, classpath, fully-qualified names, the mismatch error.10
TOTALExercise 1 · 45  +  Exercise 2 · 45  +  Viva · 10100

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

1

The Package Explorer, in Hierarchical view

Showing Lab03srccomcollege, 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.

2

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.

3

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.

4

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.

That is the whole ceremony. No zip files, no uploads, no printouts — two packages in a tidy project, one live run, and a notebook. If you also kept the 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.

LAB 3 · DONE · SYLLABUS PROGRAMMING EXERCISE 3 CLOSED

Two packages, one import,
and an app that tells five students the truth.

You built com.college.attendance.AttendanceCalculator with computePercentage() and isDetained(), and com.college.app.Main to drive it — a real package boundary, crossed by a single import line, with the college's 75% rule living in exactly one place. Then you built the same thing again from bare folders with javac -d . and java com.college.app.Main, and got byte-identical output. The official line said “A program to create Packages”, plural, and plural is what you delivered.

Four prelab drills got you there without a mark at stake: a class in a package, an import across the boundary, the same call with no import at all, and two packages built by hand in Notepad++ so that the IDE could never be mistaken for magic. You can now read cannot be resolved and is not visible as the two different problems they are, and you know why 100.0 has a decimal point in it.

[FWD → Class 17 · Exception Handling] — and it starts from the crack you already found. Hand your calculator a total of zero and it answers Infinity, or NaN, and prints it out with complete confidence. Nothing crashes; the report is simply false. Right now you have no way to make a method refuse a bad input — you can only compute something wrong and hope somebody notices. Class 17 gives you the mechanism: what an exception is, the hierarchy it lives in, and the split between checked and unchecked that decides whether the compiler forces you to deal with it. From there, Classes 17 to 20 follow one running application — a campus food-ordering app — through its real crash logs, all the way to Lab 4 · Programming Exercise 4 · Exception Handling.

Bring to Class 17: your Lab03 project, still working. We are going to break it on purpose in the first ten minutes, and it is far more instructive when the thing being broken is something you wrote yourself this afternoon.