Use this page while you work in BlueJ. Tick each step when you finish it; your ticks are saved in this browser. Answers stay hidden until you click “Reveal answer”.
Week 1 lab: Enhanced for Loop & Making Choices
This is your first Java lab. It starts from opening BlueJ, then runs the lecture examples and does the exercises from the lab instructions at the end of the lecture slides (slide 46).
Slides: Enhanced for Loop & Making Choices · Using BlueJ · Variables and Types · Module Overview
0 Put this page and the chat side by side
You will have this page on the left and the course chat on the right. Ask the chat whenever you are stuck.
- Click this button:
It opens the chat in a new tab and then tries to bring you back here. Most browsers still switch to the new tab anyway. That is normal: just click back on this tab. - Now put the two tabs side by side:
Chrome: right-click this tab at the top of the window → Add tab to new split view → then pick the Grok tab.Edge: click the three dots (…) next to the address bar → Split screen → then select the Grok tab.
- Type your questions into the chat on the right. This page has no ask box.
Reveal answer
You should see this walkthrough on the left and the Grok chat on the right.
1 Open BlueJ and the enhanceForChoices project
- Download enhanceForChoices.zip (the Original lab code). Do not unzip it yourself.
- Open BlueJ from the Windows Start menu. (Can’t see it? Type
BlueJin the search bar.) The first time, it is an empty grey window. - Click Project → Open ZIP/JAR… → find
enhanceForChoices.zip→ Open. - BlueJ unzips it into a folder called
enhanceForChoices, next to the zip, and opens it. - Look at the yellow boxes. Drag them around if you like; your layout may look different from the slide.
.java file with the same name.Examples have normal names (HelloWorld, HelloPlaces, HomeTown, EstateAgent). Exercises start with Ex_. Model answers start with Sol_.
enhanceForChoices folder (or double-click package.bluej inside it).Reveal answer
You should see yellow class boxes, including HelloWorld, HelloBrighton, HelloPlaces, HomeTown, EstateAgent, StarRating, Ex_HomeTown, Ex_EstateAgent_Switch, Ex_IfLoop_NurseryRhyme, Ex_StartRating_Challenging, and the Sol_ classes (Sol_HomeTown, Sol_EstateAgent_Switch, Sol_IfLoop_NurseryRhyme, Sol_StarRating). That is 14 classes, plus a small README note icon.
2 Open HelloWorld and compile it
- Double-click the yellow HelloWorld box. An editor window opens with coloured Java code.
- Read the comments in it. For now, focus on one line:
System.out.println("Hello World"); - Click Compile at the top of the editor window (or close it, right-click the box → Compile).
- Look at the box in the main window. What changed?
.java file you wrote into bytecode that the Java Virtual Machine can run. Python has no separate step like this. If there is a mistake, it will not compile, and BlueJ shows an error.public class HelloWorld {
public void run() {
System.out.println("Hello World");
}
public static void main(String[] args) {
new HelloWorld().run();
}
}class HelloWorld:
def run(self):
print("Hello World")
HelloWorld().run()public class HelloWorldstarts the class. The name matches the file name.- Curly brackets
{ }show where the class and each method start and end. Python uses a colon and indentation instead. Every{needs a matching}. Click next to a bracket in BlueJ and its partner lights up. - Semicolon
;ends the instruction. Python uses the end of the line. Forget it and BlueJ says';' expected. System.out.println("Hello World")is Python’sprint("Hello World").mainis where Java starts. Here it just runsrun().
def. HelloWorld has two: run() and main(). Instructions live in methods; methods live in classes.; at the end of a Java instruction. It means “this instruction ends here”.public static void yet; just leave those lines as they are.Reveal answer
The box loses its stripes (its shading). That means HelloWorld has compiled. At the bottom of the editor BlueJ says Class compiled - no syntax errors.
3 Run HelloWorld and find the terminal
- Right-click the HelloWorld box. Two new options are at the top of the menu.
- Click void main(String[] args). A small box appears; click OK.
- A new window opens. Read what it says.
- Now try the second way: right-click HelloWorld → new HelloWorld() → OK. A red box appears at the bottom left. Right-click the red box → void run().
The first way (void main) is the standard way to run a Java program. main is always the starting point.
Reveal answer
The terminal window shows Hello World. The second way shows Hello World again, on a new line. Job done: your first Java program has run.
4 Make a mistake on purpose, then duplicate a class
- Open HelloWorld. Delete the semicolon at the end of the
printlnline. - Click Compile. Read the message at the bottom of the editor.
- Put the semicolon back. Compile again.
- Now close the editor. Right-click HelloWorld → Duplicate… → name it
HelloExperiment(start with a capital letter) → OK. - Open HelloExperiment, change
"Hello World"to"Hello Charlie", compile and run it.
System.out.println("Hello Charlie");print("Hello Charlie")Errors are not failures. They are a normal part of programming. Duplicating lets you experiment while keeping the original safe.
public class HelloExperiment and new HelloExperiment().run();. BlueJ usually renames these for you, but check.Reveal answer
Without the semicolon BlueJ highlights the line and says ';' expected; the box gets red cross-hatches. With it back, it compiles again. HelloExperiment prints Hello Charlie.
5 Run HelloBrighton: four instructions in order
- Open HelloBrighton and read it. Count the
printlnlines. - Compile it, then run it (right-click → void main → OK).
- Put your “lazy hat” on: what is repeated?
System.out.println("Hello World");
System.out.println("Hello Europe");
System.out.println("Hello UK");
System.out.println("Hello Brighton");print("Hello World")
print("Hello Europe")
print("Hello UK")
print("Hello Brighton")This is sequence: Java runs the instructions in the order you give them, top to bottom.
Reveal answer
Four lines:
Hello World
Hello Europe
Hello UK
Hello BrightonThe repeated part is System.out.println("Hello ..."), typed four times. A loop can do this with one println.
6 HelloPlaces: an array and an enhanced for loop
- Open HelloPlaces. Compile and run it. Compare the output with HelloBrighton.
- Duplicate it as
HelloPlaces2. Add two more places to the array, for example"Hove"and"Lewes"(commas between them, quotes round each). - Change
"Hello "to"Bonjour ". Compile and run.
String[] placeList = {"World", "Europe", "UK", "Brighton"};
for (String place: placeList)
{
System.out.println("Hello " + place);
}placeList = ["World", "Europe", "UK", "Brighton"]
for place in placeList:
print("Hello " + place)String[] means “an array of Strings”. It is like a Python list, but it has a fixed length and only one type. The values go in curly brackets with commas, and the line ends with a semicolon.Enhanced for loop. for (String place : placeList) { ... } means “for each String in placeList, copy it into place and run the body”. It stops after the last item. Read the colon : as Python’s in. The body goes in curly brackets.
"Hello " + place joins two Strings, just like in Python. placeList and place are variables: named boxes for data.
};.Reveal answer
HelloPlaces prints exactly the same four lines as HelloBrighton, with only one println. Your version prints six lines:
Bonjour World
Bonjour Europe
Bonjour UK
Bonjour Brighton
Bonjour Hove
Bonjour Lewes7 HomeTown: your first if
- Open HomeTown. Find the new variable
homeand theifinside the loop. - Before you run it, predict: which place gets an extra message?
- Compile and run it.
String home = "Brighton";
for (String place: placeList)
{
System.out.println("Hello " + place);
if (place.equals(home)) {
System.out.print("there's no place like home, ");
System.out.println("my favourite place is " + place);
}
}home = "Brighton"
for place in placeList:
print("Hello " + place)
if place == home:
print("there's no place like home, ", end="")
print("my favourite place is " + place)- if. The test goes in round brackets. The block in curly brackets runs only when the test is true. Python writes
if test:and indents. .equalsversus==. To compare text in Java, writeplace.equals(home). Do not writeplace == home.==checks whether two things are the very same object in memory, so it can say false even when the letters match. In Python==is fine for text; in Java use==for numbers and.equalsfor Strings.- print versus println.
System.out.printprints and stays on the same line (Pythonprint(..., end="")).System.out.printlnprints and then moves to a new line (a normal Pythonprint). Here they build one line from two pieces.
{ at the end of the if line. BlueJ highlights the matching }, and the inside of the if has its own background colour.Reveal answer
Only Brighton gets the extra message:
Hello London
Hello Paris
Hello Brighton
there's no place like home, my favourite place is Brighton
Hello New York8 Exercise: Ex_HomeTown part 1 (add an else)
- Open Ex_HomeTown and read the instructions at the top. The code is a copy of HomeTown.
- After the closing
}of the if, addelse { ... }. - Inside the else, print
I've never been therewithSystem.out.println. - Compile and run.
if (place.equals(home)) {
...
} else {
System.out.println("I've never been there");
}if place == home:
...
else:
print("I've never been there")else is the “otherwise” part: its block runs when the test is false. No test and no colon after else in Java.
'else' without 'if'? The else must come straight after the if’s closing }. Check you did not put a ; after the }, or an extra }.Reveal answer
The if part becomes:
if (place.equals(home)) {
System.out.print("there's no place like home, ");
System.out.println("my favourite place is " + place);
} else {
System.out.println("I've never been there");
}Hello London
I've never been there
Hello Paris
I've never been there
Hello Brighton
there's no place like home, my favourite place is Brighton
Hello New York
I've never been there9 Exercise: Ex_HomeTown part 2 (else if for London)
- Still in Ex_HomeTown: give an opinion on London as well.
- Between the if block and the else, insert
else if (place.equals("London")) { ... }. - Inside it, print your own opinion of London. Any message is fine.
- Compile and run.
if (place.equals(home)) {
...
} else if (place.equals("London")) {
System.out.println("London is big and busy");
} else {
...
}if place == home:
...
elif place == "London":
print("London is big and busy")
else:
...if / else if / else. Java tests each condition in order and runs the first block whose test is true, then skips the rest. If none is true, the else runs. Java else if = Python elif.
"London" (it must match the array exactly), and that your else if is before the else.Reveal answer
One working version (also in the commented zip as Step06_HomeTown_explained):
if (place.equals(home)) {
System.out.print("there's no place like home, ");
System.out.println("my favourite place is " + place);
} else if (place.equals("London")) {
System.out.println("London is big and busy, but I like visiting");
} else {
System.out.println("I've never been there");
}Hello London
London is big and busy, but I like visiting
Hello Paris
I've never been there
Hello Brighton
there's no place like home, my favourite place is Brighton
Hello New York
I've never been there10 EstateAgent: a chain of ifs
- Open EstateAgent. The array is now rooms:
{"hall", "kitchen", "lounge", "kitchen", "bedroom", "hall"}. - Find the chain of
if/else if/else. How many tests are there? - Find where it uses
printand where it usesprintln. - Compile and run.
if (room.equals("kitchen")) {
System.out.print("Can you smell the coffee? ");
} else if (room.equals("bedroom")) {
System.out.print("Plenty of room for all your clothes.");
} else {
System.out.print("What is this room used for?");
}if room == "kitchen":
print("Can you smell the coffee? ", end="")
elif room == "bedroom":
print("Plenty of room for all your clothes.", end="")
else:
print("What is this room used for?", end="")Each comment uses print, so it joins the “Here we are in the …” text on the same line. The empty System.out.println(); at the end of the loop body finishes the line (Python print()).
The code works, but every test checks the same variable. The next step does it more neatly with a switch.
System.out.println(); is still inside the loop (before the loop’s closing }).Reveal answer
Four tests (kitchen, bedroom, lounge, hall) plus the final else.
Here we are in the hall. Nice and big windows.
Here we are in the kitchen. Can you smell the coffee?
Here we are in the lounge. Notice the original fireplace.
Here we are in the kitchen. Can you smell the coffee?
Here we are in the bedroom. Plenty of room for all your clothes.
Here we are in the hall. Nice and big windows.11 Exercise: Ex_EstateAgent_Switch
- Open Ex_EstateAgent_Switch. It is almost empty: just a comment showing the shape of a switch.
- Copy everything inside EstateAgent’s class (the
run()andmain()methods) into the Ex class, between its curly brackets. - In
main, changenew EstateAgent()tonew Ex_EstateAgent_Switch(). - Replace the whole if / else if / else chain with a
switch (room): onecaseper room, each ending inbreak;, anddefault:for anything else. - Compile and run. The output should be the same as EstateAgent’s.
switch (room) {
case "kitchen":
System.out.print("Can you smell the coffee? ");
break;
case "bedroom":
System.out.print("Plenty of room for all your clothes.");
break;
default:
System.out.print("What is this room used for?");
}match room: # Python 3.10+
case "kitchen":
print("Can you smell the coffee? ", end="")
case "bedroom":
print("Plenty of room for all your clothes.", end="")
case _:
print("What is this room used for?", end="")switch / case / break. switch (room) looks at the value of room and jumps to the case with the same value. A case label ends with a colon :, and there are no curly brackets round each case. break; means “I’m done, leave the switch”. Without it, Java falls through into the next case. default: is the “anything else” case, like a final else; it needs no break because it is last.
break; is missing, so it fell through. Error cannot find symbol: class EstateAgent? You forgot to change the name in main.Reveal answer
One working version (compare with Sol_EstateAgent_Switch):
public class Ex_EstateAgent_Switch{
public void run() {
String[] rooms = {"hall", "kitchen", "lounge", "kitchen", "bedroom", "hall"};
// Loop: once for each room, stopping after the last "hall".
for (String room: rooms){
System.out.print("Here we are ");
System.out.print("in the " + room + ". ");
// SWITCH: Java looks at the value of room and jumps to the case with the same value.
// Each case ends with break; which means "I'm done, leave the switch now".
// Without break, Java would carry on into the next case (this is called fall-through).
// default: runs when no case matches, like a final else.
// Notice: a case label ends with a colon : and there are no { } around each case.
// Python 3.10+: match room: case "kitchen": ... case _: ...
switch(room){
case "kitchen":
System.out.print("Can you smell the coffee? ");
break;
case "bedroom":
System.out.print("Plenty of room for all your clothes.");
break;
case "lounge":
System.out.print("Notice the original fireplace.");
break;
case "hall":
System.out.print("Nice and big windows.");
break;
default:
// The last case needs no break: there is nothing after it to fall into.
System.out.print("What is this room used for?");
}
System.out.println(); // finish printing the line
} // end of loop body
}
public static void main(String[] args){
new Ex_EstateAgent_Switch().run();
}
}The output is the same six lines as EstateAgent.
12 Check your work against the Sol_ classes
- Only now, open Sol_HomeTown. Compare it with your Ex_HomeTown. Run it.
- Open Sol_EstateAgent_Switch. Compare it with yours. Run it.
- Note one thing that is different from yours.
Reveal answer
Sol_HomeTown only does part 1 (the else); it has no London part. It also has a tiny slip: its first print has no comma and space, so Brighton prints there's no place like homemy favourite place is Brighton. Yours (copied from HomeTown) keeps "there's no place like home, ", which is right.
Sol_EstateAgent_Switch prints “Here we are ” and “in the …” with two separate prints, but the output is the same as EstateAgent.
13 Optional: StarRating, a switch without break optional
- Open StarRating and read the comment at the top.
- Predict the output for ratings 1, 3 and 5. Then compile and run.
- Challenge from the lecture: duplicate it as
StarRating2and rewrite the switch with abreakafter every case, keeping the same output. (The lecturer’s version is in the comment at the bottom of StarRating.java.)
switch (rating){
case 5: System.out.print("★");
case 4: System.out.print("★");
case 3: System.out.print("★");
case 2: System.out.print("★");
case 1: System.out.print("★");
break;
default:
System.out.print("Invalid rating");
}stars = {5: "★★★★★", 4: "★★★★", 3: "★★★",
2: "★★", 1: "★"}
print(stars.get(rating, "Invalid rating"), end="")
# Python's match cannot fall through,
# so there is no direct copy of this trick.Here the case values are numbers (case 5:) because rating is an int (a whole number). There is no break until case 1, so Java jumps in at the matching case and falls through every case below it.
? instead of stars? That is just the font in the terminal; the program is fine.Reveal answer
Rating 1: ★
Rating 3: ★★★
Rating 5: ★★★★★With a break after every case, each case prints all its stars at once, for example case 3: System.out.print("★★★"); break;. See Step09 in the commented zip.
14 Optional: Ex_IfLoop_NurseryRhyme optional
- Open Ex_IfLoop_NurseryRhyme. It prints “10 Green Bottles” one println at a time (and skips the middle).
- Read the hints at the bottom. First, comment out the old code: put
//at the start of each println line, so you can still see it. - Make an array of the number words:
"ten", "nine", ... "one", "no". - Loop over it with an enhanced for loop. Use if statements for the first and last verses, which are slightly different, and for “bottle” versus “bottles”.
if (! bottleAmount.equals("ten")) {
System.out.println("there'll be " + line);
}if bottleAmount != "ten":
print("there'll be " + line)! means not. ! bottleAmount.equals("ten") is true for every word except “ten”. Python writes != or not.
Sol_IfLoop_NurseryRhyme (the lecturer calls it “the laziest version”).Reveal answer
The model answer builds each line in a String variable:
for (String bottleAmount: bottleAmountList) {
String bottlesOrBottle = "bottles";
if (bottleAmount.equals("one")) {
bottlesOrBottle = "bottle";
}
String line = bottleAmount + " green " + bottlesOrBottle + ", hanging on the wall";
if (! bottleAmount.equals("ten")) {
System.out.println("there'll be " + line);
}
if (! bottleAmount.equals("no")) {
System.out.println(line);
System.out.println("and if one green bottle accidentally fall,");
}
}It prints the whole song, from ten down to “there’ll be no green bottles, hanging on the wall”.
15 Optional: Star Ratings with two arrays (challenging) optional
For experienced students. Don’t worry if this is too much in Week 1.
- Open Ex_StartRating_Challenging (the file name has a typo: “Start” for “Star”). Read the task at the top.
- There are two arrays:
hotels(names) andratings(numbers). Print each hotel with its stars, likeGrand Plaza (5 stars): ★★★★★. - Reuse the star switch from StarRating (no breaks, fall-through).
- Compare with Sol_StarRating. (The comment in the Ex file says the solution is called HotelRating, but in the project it is Sol_StarRating.)
for (int i = 0; i < hotels.length; i++) {
System.out.print(hotels[i] + " (" + ratings[i] + " stars): ");
// ... the star switch on ratings[i] ...
System.out.println();
}for i in range(len(hotels)):
print(hotels[i] + " (" + str(ratings[i]) + " stars): ", end="")
# ... the stars ...
print()To walk through two arrays together you need a counter, i. The model answer uses a normal for loop, which is not taught until later (the roadmap lists for loops for Week 3). hotels[i] gets item number i, counting from 0, like a Python list.
Reveal answer
Output (from Sol_StarRating):
Grand Plaza (5 stars): ★★★★★
Seaside Inn (3 stars): ★★★
Budget Stay (1 stars): ★
Royal Palace (4 stars): ★★★★The full commented answer is Step11 in the commented zip.
How to submit this lab
No lab submission was found for this week. Every part of the CI401 course on Student Central was checked on 17 October 2026: the week pages, the slides, the announcements, Assessment and Feedback Information, Assessment Submission Points, the module roadmap and the assessment brief. None of them gives any steps for submitting, demonstrating or getting sign-off for lab work. So there is nothing to hand in for this lab.
This matches what the Module Overview slides say (slide 12): “Weekly lab exercises are practice activities - they are not directly assessed. They are there to help you practise the programming techniques covered in the module and prepare you for the coursework.” (Module Overview slides)
What the lab is practice for: the coursework
- The module’s only assessment is the coursework project.
- Deadline: 22 January 2027 at 14:00.
- Where: online, through MyStudies.
- What you hand in: your project code as a zip file, plus a technical report (PDF or Word).
- Full details are expected around Week 8.
Lab work is good practice for it. Keep your own lab code (the unzipped project folder BlueJ made), so you can look back at it later.
If you ever need to hand in anything based on this week’s lab, use the Original lab code (the lecturer’s zip), not the commented version.
You are done when
- HelloWorld compiles and prints
Hello Worldin the terminal when you choose void main. - Ex_HomeTown runs and prints, for each place:
Hello ..., then “I’ve never been there” for Paris and New York, your London opinion for London, and the home message for Brighton. - Ex_EstateAgent_Switch compiles and prints the same six lines as EstateAgent, using a switch with a
break;after each room. - You can say in one sentence why you write
place.equals(home)and notplace == home.
Commented versions of every example and exercise: Commented version (for learning only). For anything you hand in, use the Original lab code.