- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Java Base Camp: References
The base camp's logistics depot keeps supplies moving for mountain expeditions. Climbers check out crates of gear, gear items get relabeled and reweighed in the field, and dispatchers need to know exactly which changes are visible to whom. Recent bugs have shipped: a relabeled gear item silently changed weight in someone else's crate, a lookup crashed with NullPointerException on an unregistered climber, and two 'equal' gear tags failed a comparison. You are the engineer assigned to harden the ledger's core reference-handling code before the next expedition season.
Lab Info
Table of Contents
-
Challenge
Step 1: Meet the base camp gear ledger
Welcome to the base camp logistics depot
The base camp's logistics depot runs the supply operation for mountain expeditions. Climbers check out crates of gear, gear items get relabeled and reweighed out in the field, and dispatchers depend on the ledger to know exactly which changes are visible to whom.
The ledger is built from three plain classes you'll find under
src/main/java/lab/:GearItem-- a mutable piece of gear with alabeland aweightKg, plus getters and setters.Crate-- holds acrateIdand aList<GearItem>of the gear packed inside it.Climber-- holds anameand theCratethey've been assigned, which may benullif they haven't checked one out yet.
There's also an
ImmutableGearSpecrecord, used later in the lab to contrast a truly immutable value with the mutableGearItemclass. ## Three bugs shipped last season- A dispatcher relabeled a
GearItemin one crate and the weight silently changed in a different climber's crate too, because both crates were holding onto the same object. - A lookup for an unregistered climber threw
NullPointerExceptionin the middle of a checkout, because nothing checked whether the roster actually contained that name. - Two gear tags that were clearly "the same" failed an
==comparison, because they were two separateIntegerobjects holding the same value.
Each of these traces back to the same root cause: a shaky mental model of what a Java variable actually holds -- a primitive value copied on assignment, or a reference to a shared object on the heap. ## What you'll build
Over the next four steps you will:
- Trace, with real return values, exactly what an assignment copies for a primitive versus a
GearItemreference (Step 2). - Rework the ledger's lookups so a missing climber, crate, or gear item is caught before it can throw
NullPointerException(Step 3). - Predict and verify which mutations ripple through shared references, and contrast a
finalreference with a genuinely immutable record (Step 4). - Fix boxed-value comparisons and unboxing sums, then wire every helper together into one end-to-end ledger report (Step 5).
No code changes yet -- open the starter files under
src/main/java/lab/and locate the// TODOcomments before moving on to Step 2.info> If you get stuck, you can refer to the provided solution code for each task, available in the
solutionfolder. -
Challenge
Step 2: Trace primitive copies against shared object references
Primitives copy their value, references copy their pointer
When you assign one
doubleto another, Java copies the bits: the two variables are independent from that point on. When you assign one object reference to another, Java copies the pointer -- both variables end up pointing at the exact same object on the heap, so a mutation through either one is visible through both.CopyTraces.javahas three stub methods for proving this out with real return values instead of just reading about it. Start with the primitive case. ## Now do the same experiment with a referenceThe primitive case felt obvious once you saw it: the copy and the original never interfered with each other. A
GearItemreference behaves completely differently. Assigningoriginalto a second variable doesn't create a second gear item -- it creates a second name for the same gear item. Any setter call through either variable changes the one object both variables are looking at. ## Breaking aliasing on purposeAliasing isn't a bug by itself -- it's a bug only when you didn't intend to share state. The fix, when you need an independent copy, is to allocate a new object with the same field values and mutate that instead. This is exactly the move a dispatcher needs when reweighing gear for one crate without touching the record shared elsewhere.
-
Challenge
Step 3: Diagnose NullPointerException before it happens
NullPointerException happens at the access, not the assignment
A variable holding
nullisn't the problem by itself -- the crash happens the moment you call a method or read a field through it.LedgerLookup.javacentralizes the ledger's lookups so every place that might not find something checks fornullbefore touching the result, not after.Start with the simplest case: looking up a climber that might not be registered. ## Nulls can hide one level deeper
A crate reference can be
null, or the crate can exist with anullitems list, or the list can exist but contain anullentry where a gear item was removed without cleanup. Each of these needs its own check, in order from the outside in, before you ever call a method on what you found. ## Chaining the checksThe pattern from the last task -- check the container, then the collection, then the element -- generalizes to any depth of nesting. The next lookup walks three links (crate, its items, the first item) and needs a fallback at every one of them.
-
Challenge
Step 4: Predict aliasing effects and lock references with final
Method arguments are aliases too
Passing an object to a method doesn't pass a copy of the object -- it passes a copy of the reference, which still points at the same heap object the caller has. Anything the method does to that object through its own parameter variable is visible to the caller the moment the method returns, sometimes even before it returns.
CrateAliasing.javaputs this to the test by finding and mutating a gear item that lives inside a crate's own list. ## final freezes the variable, not the objectDeclaring a reference variable
finalonly prevents that variable from being reassigned to point at a different object later. It does nothing to stop you from mutating whatever the object contains -- adding to a list, calling a setter, anything the object's own API allows. That distinction is the difference between "this binding is fixed" and "this object never changes." ## Real immutability has no setters at allImmutableGearSpecis a record: its fields are set once in the constructor and there is no method anywhere that can change them afterward. The only way to get a "changed" spec is to build a brand-new one. Contrasting that with the mutableGearItemclass -- which happily changes in place -- makes the difference between afinalreference and a genuinely immutable object concrete. -
Challenge
Step 5: Box, unbox, and compare gear tags correctly, then wire the ledger
Boxed primitives are objects, with an identity of their own
Integer, unlikeint, is an object, so==compares object identity, not the numeric value. Java caches small boxed integers (-128 to 127), which is why small examples can look like==works fine right up until a tag id outside that range breaks the illusion.equals()is the only comparison that reliably checks the value.TagComparisons.javastarts with exactly this fix. ## Unboxing a null Double is its own crashAutoboxing and unboxing happen automatically, which is convenient right up until a
List<Double>contains anull-- unboxing that entry to a primitivedoublethrowsNullPointerExceptionjust like calling a method on a null reference would. The fix is the same shape as Step 3's null guards, just applied while summing. ## Bringing it all togetherEvery helper you've built -- safe lookups, aliasing-aware mutation, correct boxed comparisons -- exists to support one thing: a ledger report that never crashes no matter how incomplete the data is.
BasecampLedger.javais where they all get called from a single method that produces the final report. -
Challenge
Step 6: Run the application
Every task is done, and each one was graded the moment you completed it. What you have not done yet is watch the whole application run at once -- which is the only place the pieces you wrote separately become a single working program.
Start the application
Open the Terminal tab and run:
java -cp target/classes lab.MainThe program runs in the terminal and prints its output there. Every behaviour it shows is code you wrote in the previous steps, so read the output against what each task asked for -- that is the whole lab, working as one program. ### Run the checks yourself
The lab ran each task's test for you as you went, but they are ordinary tests and you can run them whenever you like. The whole suite:
mvn --batch-mode --quiet testOr one task at a time:
bash runTest.sh task_2_1Each failure names the task it belongs to, so the output tells you which step to go back to rather than which line to stare at. Two things worth trying before you finish: break something on purpose and watch the matching check fail, then put it back. Knowing what a failure looks like is worth as much as knowing what a pass looks like, and it costs you nothing here.
When you are done, everything you wrote is still in the editor tabs -- the lab is yours to keep reading.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.