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

When is this lab? Announcement, 2 October 2026: Monday lab groups 1 & 2 had no lab in Week 1; they start in Week 2 (Monday 11:00–13:00). Tuesday groups 3 & 4 ran as normal in Week 1. The Module Overview slides also say groups 1 & 2 work on the previous week’s lab, so if you are in group 1 or 2, this is the lab you do in Week 2.

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.

  1. 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.
  2. 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.

  3. Type your questions into the chat on the right. This page has no ask box.
Stuck? No split option in your browser? Just drag the two windows so each fills half the screen.
Reveal answer

You should see this walkthrough on the left and the Grok chat on the right.

1 Open BlueJ and the enhanceForChoices project

  1. Download enhanceForChoices.zip (the Original lab code). Do not unzip it yourself.
  2. Open BlueJ from the Windows Start menu. (Can’t see it? Type BlueJ in the search bar.) The first time, it is an empty grey window.
  3. Click Project → Open ZIP/JAR… → find enhanceForChoices.zip → Open.
  4. BlueJ unzips it into a folder called enhanceForChoices, next to the zip, and opens it.
  5. Look at the yellow boxes. Drag them around if you like; your layout may look different from the slide.
New word: class. A class is the container for a Java program. All Java code lives inside a class. In BlueJ each yellow box is one class, saved in its own .java file with the same name.

Examples have normal names (HelloWorld, HelloPlaces, HomeTown, EstateAgent). Exercises start with Ex_. Model answers start with Sol_.

Your work lives in the unzipped folder. BlueJ never changes the zip. Next time, BlueJ reopens your last project by itself, or use Project → Open Project… and choose the enhanceForChoices folder (or double-click package.bluej inside it).
Stuck? Cannot find Open ZIP/JAR? It is in the Project menu at the very top of the BlueJ window. On your own PC with no BlueJ yet? See the optional “Programming and Java – Additional Background and Getting Started” slides; the lab PCs already have 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

  1. Double-click the yellow HelloWorld box. An editor window opens with coloured Java code.
  2. Read the comments in it. For now, focus on one line: System.out.println("Hello World");
  3. Click Compile at the top of the editor window (or close it, right-click the box → Compile).
  4. Look at the box in the main window. What changed?
New word: compile. Compiling means Java checks your code and turns the .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.
Java
public class HelloWorld {
    public void run() {
        System.out.println("Hello World");
    }

    public static void main(String[] args) {
        new HelloWorld().run();
    }
}
Python
class HelloWorld:
    def run(self):
        print("Hello World")

HelloWorld().run()
  • public class HelloWorld starts 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’s print("Hello World").
  • main is where Java starts. Here it just runs run().
New word: method. A method is a named block of instructions, like a Python def. HelloWorld has two: run() and main(). Instructions live in methods; methods live in classes.
New word: semicolon. The ; at the end of a Java instruction. It means “this instruction ends here”.
Stuck? The Compile button is greyed out? You may be in the main window, not the editor. Use the Compile button on the left of the main window instead: it compiles every box at once. Do not worry about 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

  1. Right-click the HelloWorld box. Two new options are at the top of the menu.
  2. Click void main(String[] args). A small box appears; click OK.
  3. A new window opens. Read what it says.
  4. 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().
New word: terminal. The terminal is the text window where your program shows its output. BlueJ calls it the Terminal Window. It opens by itself when your program prints something.

The first way (void main) is the standard way to run a Java program. main is always the starting point.

Stuck? No terminal window? Look behind the BlueJ window or on the taskbar; it may have opened underneath. Or use View → Show Terminal in BlueJ.
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

  1. Open HelloWorld. Delete the semicolon at the end of the println line.
  2. Click Compile. Read the message at the bottom of the editor.
  3. Put the semicolon back. Compile again.
  4. Now close the editor. Right-click HelloWorld → Duplicate… → name it HelloExperiment (start with a capital letter) → OK.
  5. Open HelloExperiment, change "Hello World" to "Hello Charlie", compile and run it.
Java
System.out.println("Hello Charlie");
Python
print("Hello Charlie")

Errors are not failures. They are a normal part of programming. Duplicating lets you experiment while keeping the original safe.

Stuck? HelloExperiment will not run, or prints from the wrong class? Check that the code says 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

  1. Open HelloBrighton and read it. Count the println lines.
  2. Compile it, then run it (right-click → void main → OK).
  3. Put your “lazy hat” on: what is repeated?
Java
System.out.println("Hello World");
System.out.println("Hello Europe");
System.out.println("Hello UK");
System.out.println("Hello Brighton");
Python
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.

Stuck? Old output from HelloWorld is still in the terminal? That is fine. You can clear it: in the terminal window, Options → Clear.
Reveal answer

Four lines:

Hello World
Hello Europe
Hello UK
Hello Brighton

The 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

  1. Open HelloPlaces. Compile and run it. Compare the output with HelloBrighton.
  2. Duplicate it as HelloPlaces2. Add two more places to the array, for example "Hove" and "Lewes" (commas between them, quotes round each).
  3. Change "Hello " to "Bonjour ". Compile and run.
Java
String[] placeList = {"World", "Europe", "UK", "Brighton"};

for (String place: placeList)
{
    System.out.println("Hello " + place);
}
Python
placeList = ["World", "Europe", "UK", "Brighton"]

for place in placeList:
    print("Hello " + place)
New word: array. An array is a group of values of one type, kept together in one variable. 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.

Stuck? Red error after adding places? Check every place has double quotes round it, there is a comma between each pair, and the line still ends with };.
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 Lewes

7 HomeTown: your first if

  1. Open HomeTown. Find the new variable home and the if inside the loop.
  2. Before you run it, predict: which place gets an extra message?
  3. Compile and run it.
Java
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);
    }
}
Python
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.
  • .equals versus ==. To compare text in Java, write place.equals(home). Do not write place == 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 .equals for Strings.
  • print versus println. System.out.print prints and stays on the same line (Python print(..., end="")). System.out.println prints and then moves to a new line (a normal Python print). Here they build one line from two pieces.
Stuck? Not sure where the if starts and ends? Click just after the { 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 York

8 Exercise: Ex_HomeTown part 1 (add an else)

  1. Open Ex_HomeTown and read the instructions at the top. The code is a copy of HomeTown.
  2. After the closing } of the if, add else { ... }.
  3. Inside the else, print I've never been there with System.out.println.
  4. Compile and run.
Java
if (place.equals(home)) {
    ...
} else {
    System.out.println("I've never been there");
}
Python
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.

Stuck? Error '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 there

9 Exercise: Ex_HomeTown part 2 (else if for London)

  1. Still in Ex_HomeTown: give an opinion on London as well.
  2. Between the if block and the else, insert else if (place.equals("London")) { ... }.
  3. Inside it, print your own opinion of London. Any message is fine.
  4. Compile and run.
Java
if (place.equals(home)) {
    ...
} else if (place.equals("London")) {
    System.out.println("London is big and busy");
} else {
    ...
}
Python
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.

Stuck? London still says “I’ve never been there”? Check the capital L in "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 there

10 EstateAgent: a chain of ifs

  1. Open EstateAgent. The array is now rooms: {"hall", "kitchen", "lounge", "kitchen", "bedroom", "hall"}.
  2. Find the chain of if / else if / else. How many tests are there?
  3. Find where it uses print and where it uses println.
  4. Compile and run.
Java
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?");
}
Python
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.

Stuck? Everything comes out on one long line? Check that 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

  1. Open Ex_EstateAgent_Switch. It is almost empty: just a comment showing the shape of a switch.
  2. Copy everything inside EstateAgent’s class (the run() and main() methods) into the Ex class, between its curly brackets.
  3. In main, change new EstateAgent() to new Ex_EstateAgent_Switch().
  4. Replace the whole if / else if / else chain with a switch (room): one case per room, each ending in break;, and default: for anything else.
  5. Compile and run. The output should be the same as EstateAgent’s.
Java
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?");
}
Python
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.

Stuck? Kitchen also prints the bedroom comment? A 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

  1. Only now, open Sol_HomeTown. Compare it with your Ex_HomeTown. Run it.
  2. Open Sol_EstateAgent_Switch. Compare it with yours. Run it.
  3. Note one thing that is different from yours.
Stuck? Your code looks different but gives the right output? That is fine. There is usually more than one right answer.
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

  1. Open StarRating and read the comment at the top.
  2. Predict the output for ratings 1, 3 and 5. Then compile and run.
  3. Challenge from the lecture: duplicate it as StarRating2 and rewrite the switch with a break after every case, keeping the same output. (The lecturer’s version is in the comment at the bottom of StarRating.java.)
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");
}
Python
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.

Stuck? Seeing ? 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

  1. Open Ex_IfLoop_NurseryRhyme. It prints “10 Green Bottles” one println at a time (and skips the middle).
  2. 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.
  3. Make an array of the number words: "ten", "nine", ... "one", "no".
  4. 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”.
Java
if (! bottleAmount.equals("ten")) {
    System.out.println("there'll be " + line);
}
Python
if bottleAmount != "ten":
    print("there'll be " + line)

! means not. ! bottleAmount.equals("ten") is true for every word except “ten”. Python writes != or not.

Stuck? This one is deliberately a bit annoying, and completely optional. If you are stuck, open 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.

  1. Open Ex_StartRating_Challenging (the file name has a typo: “Start” for “Star”). Read the task at the top.
  2. There are two arrays: hotels (names) and ratings (numbers). Print each hotel with its stars, like Grand Plaza (5 stars): ★★★★★.
  3. Reuse the star switch from StarRating (no breaks, fall-through).
  4. Compare with Sol_StarRating. (The comment in the Ex file says the solution is called HotelRating, but in the project it is Sol_StarRating.)
Java
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();
}
Python
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.

Stuck? An enhanced for loop can only go through one array, so you cannot use it for both. That is why this needs the counter version.
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.

AI rule for the coursework. The coursework is rated RED for AI: using generative AI is not allowed, apart from checking spelling and grammar. Check the assessment brief (in the Assessment Information area on MyStudies) for the exact rules.

You are done when

  • HelloWorld compiles and prints Hello World in 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 not place == home.

Commented versions of every example and exercise: Commented version (for learning only). For anything you hand in, use the Original lab code.