- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Java Base Camp: Objects
A trail crew is scouting base camp sites along a river valley. Each candidate site is a coordinate on a grid, represented with java.awt.Point. The crew needs code that can plant an anchor camp, relocate scouts as they move, measure distances between camps, generate random candidate coordinates inside the mapped area, and finally assemble a report naming the nearest usable camp.
Lab Info
Table of Contents
-
Challenge
Step 1: Scout the trailhead base camp locator project
Base camp locator
A trail crew is scouting base camp sites along a river valley. Every candidate site is a coordinate on a grid, and Java already ships a class built for exactly this:
java.awt.Point. Over the next four steps you will plant an anchor camp, relocate scouts as they move, measure distances between camps, and finally generate random candidate coordinates so the crew can pick the nearest usable camp.The work happens entirely inside
src/main/java/lab/. Each step owns its own file, and each file already imports the classes you need (java.awt.Point,java.util.Random,java.util.List) so you can focus on the object mechanics: constructing instances, reading and writing fields, and calling instance versus static methods. ## The starter filesCampSites.java— plants a camp anchor and reads its coordinates.ScoutRoute.java— moves a scout's ownPointand measures the gap between two camps.CampSurvey.java— contrasts a static utility call with an instance call, then rolls random coordinates.BaseCampLocator.java— wires everything together into a final report.
Each file has one or more methods with a
// TODO: Task N.Mcomment marking exactly what to fill in. A// Hint:line sits underneath naming the technique to reach for, never the finished line of code. ## WhyPointfits this problemjava.awt.Pointstores anxand ayas publicintfields — you can read or writecamp.xdirectly, no getter required. It also exposes instance methods likemove(x, y),translate(dx, dy), anddistance(otherPoint)that act on the specificPointyou're holding. Keep that public-field-versus-method distinction in mind; it's the first thing that trips up developers coming from languages where fields are private by default. Once you're oriented, move to Step 2 and plant the crew's first camp.info> If you get stuck, you can refer to the provided solution code for each task, available in the
solutionfolder. -
Challenge
Step 2: Plant camp anchors and read their coordinates
Step 2: Plant camp anchors and read their coordinates
Every camp the crew marks on the map is going to be a
java.awt.Point. Before you can move scouts around or measure distances, you need a way to create that first anchor camp, drag it when a scout repositions it, and print its location for a report. All three of those live inCampSites.java. ### Building aPointPointhas a constructor that takes both coordinates at once:new Point(x, y). That's the whole API for creating one — there's no builder, no factory method, just the constructor with the two ints the crew already measured in the field. ### Fields you can write toWith the anchor camp planted, the next job is moving it.
Point.xandPoint.yare publicintfields, not private ones hidden behind getters and setters. That means relocating a camp is just an assignment:camp.x = newX. There's nothing to call, nothing to construct — you're editing the object in place, and the same reference the caller already has will show the new position afterward. ### When to reach for the getters insteadSo if the fields are public, why does
Pointalso exposegetX()andgetY()? Because those methods returndouble, notint— useful when a coordinate needs to line up with other geometry APIs that expect floating-point values, like the report format this app uses. For anything that needs to match that format, call the getter rather than reading the raw field, even though both describe the same position. WithCampSites.javadone, you can construct a camp, drag it to a new spot, and describe where it ended up. Step 3 puts a scout's ownPointin motion and measures the distance between two camps. -
Challenge
Step 3: Move scouts and measure camp distances
Step 3: Move scouts and measure camp distances
The anchor camp from Step 2 doesn't move once it's planted, but scouts do. As they hike out from camp, their position needs to update relative to where they already are, not jump to some absolute spot pulled from thin air.
Pointgives you two ways to change coordinates, and picking the wrong one silently breaks the route:move(x, y)overwrites both fields with the values you pass in, whiletranslate(dx, dy)adds those values to whateverxandyalready hold. A scout who has hiked to(12, 7)and then takes 3 steps east and 1 step north should land on(15, 8)— that's a job fortranslate, notmove. ## Comparing two camps, not just oneOnce scouts can move, the crew's next question is practical: how far apart are two candidate camps?
Pointanswers that with an instance method,distance(Point other). It's called on onePointand given another, and it returns the straight-line distance between them as adouble— no manual square-root arithmetic required. Because it's an instance method,campA.distance(campB)andcampB.distance(campA)both work and give the same answer; the method belongs to whichever object you call it on, but the math is symmetric. -
Challenge
Step 4: Tell static utilities apart from instance calls, then roll random camps
The crew has camps planted and scouts who can move between them. Now they need to compare camps: how far apart are two sites, and how do you even call the method that answers that? Java draws a sharp line between two kinds of calls. A static method belongs to the class itself and never touches any particular object's fields --
Math.abs(-5)doesn't care whichMathyou're using, because there is no such thing as "a"Mathobject. An instance method, by contrast, belongs to one specific object and reads or uses that object's own state --campA.distance(campB)only makes sense becausecampAis a realPointwith its ownxandy. OpenCampSurvey.javaand start with the static case. That gap only looked at one axis. To see the true straight-line distance between two camps -- accounting for both east-west and north-south offset -- you need a method that already knows how to combine both.Pointsupplies exactly that as an instance method:campA.distance(campB)usescampA's own coordinates againstcampB's, so the call only makes sense hung off a realPointobject, unlike the staticMath.absyou just called on the class itself. With distance measurement in hand, the crew's last problem is generating fresh candidate sites to measure in the first place.java.util.Randomalso follows the instance rule: you create aRandomobject, and callingnextInt(bound)on that particular instance produces a pseudo-randomintsomewhere in the half-open range[0, bound)-- never equal tobounditself. That exclusive upper limit matters here because it letsboundstand for the width or height of the mapped area without ever generating a coordinate that falls just outside it. -
Challenge
Step 5: Assemble the base camp locator report
You have an anchor camp that can be planted and moved, and you know how to measure the distance between two points. Now put those pieces to work: the crew needs a batch of candidate sites to choose from, a way to rank them against the anchor, and a one-line report naming the winner. All three pieces live in
BaseCampLocator.java, and each one builds directly onjava.awt.Pointand the instance methods you have already used. Random candidate generation is the first piece: the crew wants a pool of grid coordinates to scout, not just one.java.util.Randomgives you that withnextInt(bound), which returns a value in[0, bound)-- exactly the range a grid coordinate needs. Call it twice per candidate, once for x and once for y, and keep reusing the sameRandominstance across the loop so each call advances the sequence instead of restarting it. With a pool of candidates in hand, the crew needs to know which one sits closest to the trailhead anchor.Pointalready gives you the comparison metric: callingdistance(...)on one point with another as the argument returns the straight-line distance between them. Ranking candidates is just a matter of calling that instance method once per candidate and remembering the smallest result you have seen so far. The last piece turns that ranking into something the crew can read.buildReportshould not repeat the search logic -- it already hasfindNearestCampto call for the winningPoint, andanchor.distance(...)to get the winning distance. Pull the x and y out of eachPointwithgetX()/getY(), and assemble the report string in the exact layout the crew expects so it can be dropped straight into the day's field notes. -
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:
mvn --batch-mode --quiet compile && 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.