← Back to CI401
CI401 Introduction to Programming · University of Brighton · Week 1

Module Introduction; Enhanced for Loop & Making Choices

Sunday prep for your first Java week. Read it before the lecture and lab. It starts with how the module works and how to use BlueJ, then follows the lecture slides in order.

Files: Module Overview · Using BlueJ · Variables and Types · main lecture: Enhanced for Loop & Making Choices · lab project enhanceForChoices.zip · optional: Programming and Java background

What to do today (about 60 minutes)

  1. 5 min – Read “The module” below: how CI401 works, when labs are, and how it is assessed.
  2. 10 min – Read “BlueJ” and “Java basics”. This is the shape of every Java program you will see this term.
  3. 5 min – Read “Variables”: boxes for data, and arrays.
  4. 10 min – Read “Loops” (the enhanced for loop). Click through Tracer 1.
  5. 15 min – Read “Choices” (if, else, else if, switch). Click through Tracers 2, 3 and 4.
  6. 8 min – Try the four “What will it print?” questions. Guess first, then reveal.
  7. 7 min – Read the lab tasks, then do the 8-question quiz. Aim for 6 or more. Your answers are saved on this computer.

Do not worry if the code looks scary. The slides say it plainly: almost every word and symbol may raise a question at first, and that is normal. Focus on this week’s ideas; the rest builds up step by step.

1. The module: CI401 Introduction to Programming

What is programming? A program (also called software or an application) is a set of instructions that tells a computer what to do. Programming is writing those instructions. A programming language is the language you write them in. Programming tools help you write, compile, debug and run programs. An IDE (Integrated Development Environment) puts all those tools in one place.

Why Java? Java is a high-level, general-purpose, object-oriented language, used a lot in teaching, research and industry. The slides stress: this is a programming module that happens to use Java. The ideas carry over to other languages, including the Python you already know.

BlueJ is the IDE the module uses. It is simple, made for beginners, and it is on the lab PCs. (Eclipse and IntelliJ are there too, but all the slides use BlueJ.)

How you learn

How you are assessed

One coursework project. You need at least 40 out of 100 to pass. The details (the Assessment Brief) are in the Assessment Information area on MyStudies, but the slides say you do not need to read it yet. The project is introduced around Week 8.

Who to ask

Module leader: Shine Shan (J.Shan@brighton.ac.uk, room C519, Cockcroft 5th floor). Lab tutors: Alexey Chernov, Karina Rodriguez Echavarria and William Wilkinson. You can ask in labs, by email, or by chat with any staff member.

From the Module Overview slides.

2. Getting started with BlueJ

This part is about using BlueJ as a tool, not about Java itself. Each week you get a new project zip; you open it the same way every time.

  1. Start BlueJ from the Windows Start menu (or type BlueJ in the search bar). The first time, it is an empty grey window.
  2. Download the project zip, for example enhanceForChoices.zip.
  3. In BlueJ click Project → Open ZIP/JAR…, pick the zip, and open it. BlueJ unzips it into a folder with the same name, next to the zip.
Your work lives in the unzipped folder, not in the zip. BlueJ never changes the zip, so keep it as a backup. Next time, BlueJ reopens your last project by itself, or use Project → Open Project… and pick the unzipped folder (or double-click the file called package.bluej inside it).

The yellow boxes. When a project opens you see yellow boxes. Each yellow box is one class, and its name is the class name. You can drag the boxes around.

New word: class. A class is the container that holds a Java program, or one part of a bigger program. All Java code must live inside a class. In BlueJ each yellow box is one class, saved in its own .java file with the same name.

Compile, then run

Running a Java program takes two steps:

New word: compile. Compiling means Java checks your code and translates it from the .java file you wrote into bytecode (a .class file) that the Java Virtual Machine can run. If your code has a mistake, it will not compile, and BlueJ shows you an error. Python has no separate step like this: you just run the file.
New word: terminal. The terminal is the text window where your program shows its output (and, from Week 2, where you type input). BlueJ calls it the Terminal Window and opens it by itself when your program prints something.

Editing. Double-click a box to open its code. After any change, compile again before you run. If there is a mistake, BlueJ highlights it and the box shows red cross-hatches. Fix it and compile again. The slides say: errors are not failures; they are a normal part of learning.

Duplicating. To experiment without spoiling the original: right-click the class → Duplicate… → give it a new name starting with a capital letter (for example HelloExperiment).

Workflow: open project → open class → compile → run → edit → compile again → duplicate when useful.

Code essentials (what matters to Java)

Comments: // and /* … */. Two slashes start a comment that lasts to the end of the line. A comment over several lines goes between /* and */. Use comments to explain your code, to leave notes, or to switch a line off (“comment it out”).
Show me the Python version
# This is a comment in Python
print("Hello")  # a comment after code
"""Python has no true block comment;
a triple-quoted string is often used instead."""

Java // is exactly like Python #. Java’s /* ... */ can cover many lines; in Python you would put # on every line.

From the Using BlueJ slides, including the “Extra Reading – Code Essentials” part.

3. Java basics: reading HelloWorld

The lecture’s first program is HelloWorld. Most of it is the “wrapping” every Java program needs. The slides say: for now, focus on the one key instruction, System.out.println("Hello World");. You do not need to understand the rest yet, but here is what each part means, so it is not a mystery.

// HelloWorld: the first Java program. It prints Hello World.

// Start the class called HelloWorld. Everything else lives inside its { }.
public class HelloWorld {

    // A method called run. It holds this program's instructions.
    public void run() {
        // The important instruction: show "Hello World" on the screen,
        // then move to a new line. The ; ends the instruction.
        System.out.println("Hello World");
    }   // this } closes run()

    // main: the method Java starts from.
    public static void main(String[] args) {
        // Make a HelloWorld object and call its run() method.
        new HelloWorld().run();
    }   // this } closes main()

}   // this } closes the class

A simple way to picture the structure (from the comments in the lab code): a class is a house, a method is a room, an instruction is an item in the room. Instructions live inside methods; methods live inside classes.

class and public. public class HelloWorld starts a class called HelloWorld. public means other code (and BlueJ) is allowed to use it. The class name must match the file name exactly (HelloWorld.java) and should start with a capital letter.
Show me the Python version
class HelloWorld:
    ...   # the class body is indented

Python can also make classes, but a short Python program does not need one. In Java, every program must be inside a class, so even the tiniest program starts with public class ....

Curly brackets { }. They mark where something starts and ends: the class, a method, and (later) a loop or an if. Every { needs a matching }. In BlueJ, click next to a bracket and its partner is highlighted.
Show me the Python version
def run():
    print("Hello World")   # indented = inside run
print("not inside run")    # back out = outside

Python uses a colon and indentation to show what is inside what. Java uses { and } instead, and does not care about the indentation (but you should still indent, for humans).

New word: method. A method is a named block of instructions that you can run, like a Python function made with def. HelloWorld has two methods: run() and main().
void and round brackets ( ). public void run() makes a method called run. void means “this method does a job but does not hand back an answer”. The round brackets are where a method’s inputs would go; run() has none, so they are empty. Round brackets are also used when you call a method: println("Hello World").
Show me the Python version
def run():          # a function with no inputs
    print("Hello World")

run()               # call it: round brackets again

Same idea as Python: brackets after a name mean a method/function. Python’s def does not say whether it returns something; Java says void when it returns nothing.

main, static and String[] args. public static void main(String[] args) is the special method Java starts from. In BlueJ you run a program by choosing void main(String[] args). static means main can run before any HelloWorld object exists. String[] args is an array (a list) of Strings that we never use. Copy this line exactly as it is.
Show me the Python version
def main():
    HelloWorld().run()

if __name__ == "__main__":   # the usual Python start point
    main()

Python just runs the file from the top. Java always starts at main. Here main only does one thing: it starts run(), where the real instructions are.

new and the dot .. new HelloWorld() makes a new object from the HelloWorld class. .run() then calls that object’s run method. The dot means “the thing on the right, belonging to the thing on the left”.
Show me the Python version
HelloWorld().run()   # make an object, call its run method

Python makes an object just by calling the class name. Java needs the word new in front. The dot works the same in both languages.

System.out.println. Prints the text in the brackets on the screen (in the terminal) and then moves to a new line. Read the dots as: System (Java’s system tools) → out (the screen output) → println (print a line).
Show me the Python version
print("Hello World")

Exactly Python’s print, just longer to type. You will meet its partner System.out.print (no new line) later this week.

String and double quotes. "Hello World" is a String: a piece of text. Strings go in double quotes. String is spelt with a capital S.
Show me the Python version
message = "Hello World"   # a str
print(type(message))     # <class 'str'>

Java String = Python str. One difference: Python lets you use single or double quotes; Java Strings must use double quotes.

New word: semicolon. The semicolon ; at the end of a Java instruction means “this instruction ends here”. Every instruction needs one. Forgetting it is the most common beginner error; BlueJ says ';' expected.
Semicolon ;. Ends every instruction (but not the lines that open a block with {, and not a closing }).
Show me the Python version
print("Hello World")      # the end of the line ends it
print("a"); print("b")   # ; only needed to put two on one line

In Python the end of the line ends the instruction. In Java the semicolon does, which is why Java does not care about line breaks.

From the main lecture (slide 4), the HelloWorld.java comments, and the BlueJ slides.

4. Variables and types: the basics

The lecture asks you to read the short “Variables and Types – The Basics” slides first. Variables are covered properly later in the module; this is just enough for this week.

Boxes on a table. Picture some boxes. Each box has a name, a shape (size), and holds one item at a time. In programming: box = variable, shape = type, item inside = value. So each variable has a name and a type, and stores one value of that type.

// Make a box called age that holds whole numbers, and put 20 in it.
int age = 20;
// Put 25 in the same box. The old value 20 is thrown away.
age = 25;
Making a variable: type name = value; int age = 20; means: int is the type (whole numbers), age is the name, 20 is the value. The = means “put the value on the right into the box on the left”. Saying the type and name is called declaring the variable; putting the first value in is initialising it. Later you change the value with just age = 25; (no type the second time).
Show me the Python version
age = 20    # Python works out the type by itself
age = 25    # replace the value

Python does not make you say the type. Java does, the first time, and then the box can only ever hold that type: you cannot put text into an int.

Common types (just recognise them for now)

// int: a whole number
int count = 10;
// double: a number with a decimal point
double price = 9.99;
// String: text, in double quotes
String city = "Brighton";
int, double, String. int = whole numbers, double = decimal numbers, String = text.
Show me the Python version
count = 10          # int
price = 9.99        # float
city = "Brighton"   # str

Java int = Python int; Java double = Python float; Java String = Python str.

From one box to many: arrays

Sometimes you need many boxes of the same shape, joined together, like train coaches.

New word: array. An array is a group of values of one type, kept together in one variable, in order. int[] scores = {80, 75, 90}; is three whole-number boxes in a row. Everything inside one array must be the same type.
// An array of 3 whole numbers, kept together in the variable scores
int[] scores = {80, 75, 90};
// An array of 4 Strings, kept together in the variable cities
String[] cities = {"London", "Tokyo", "York", "Brighton"};
Square brackets [] and { , , } for arrays. int[] means “an array of ints”; String[] means “an array of Strings”. The starting values go inside curly brackets, separated by commas, and the line ends with a semicolon.
Show me the Python version
scores = [80, 75, 90]
cities = ["London", "Tokyo", "York", "Brighton"]

A Java array is like a Python list, but it has a fixed length and can only hold one type. Python uses square brackets for the values; Java uses curly brackets here.

Now we can store many values. The next question is: how do we do something with every item easily? That is the enhanced for loop.

From the Variables and Types slides.

5. Three basic control structures

Every program, however big, is built from just three kinds of structure:

  • Sequence – do things in order, step by step, without skipping.
  • Selection (decision) – ask a question and choose what to do (if…else, switch…case).
  • Loop (repetition, iteration) – repeat things.

The slides suggest a good habit: when you learn a new language, ask “how does this language do sequence, selection and iteration?”. You already know the Python answers.

6. From HelloWorld to HelloBrighton: spotting repetition

HelloBrighton prints four messages instead of one. That is sequence: Java runs the instructions in the order given.

// HelloBrighton: four instructions, run in order (sequence).
public class HelloBrighton
{
    public void run()
    {
        // Each line prints one message and moves to a new line.
        System.out.println("Hello World");
        System.out.println("Hello Europe");
        System.out.println("Hello UK");
        System.out.println("Hello Brighton");
    }

    // Java starts here and calls run().
    public static void main(String[] args) {
        new HelloBrighton().run();
    }
}

Put your “lazy hat” on: we typed System.out.println("Hello ...") four times. Wouldn’t it be better to say “here is a list of places; say Hello to each one”?

Good programmers are lazy. Whenever you repeat yourself in code, ask “is there a way not to?”. Really it is about writing code that is short and general, so it is easier to understand, test, reuse and change. The slides also warn about copy-paste: repeated code is hard to test and change, code you do not understand may not do what you need, and using other people’s code professionally needs their permission.

7. Loops in Java and the enhanced for loop

A loop repeats a set of actions. For some loops, a condition decides whether to carry on; when it becomes false, the loop stops. Java has four kinds:

LoopWhat it doesWhen
enhanced for (for-each)goes through the items in an array or collectionthis week
forrepeats a block a fixed number of timeslater
whilerepeats while a condition is true (tests first)Week 2
do whilerepeats while a condition is true (tests after)later

The enhanced for loop goes through an array one item at a time. It is simpler and safer than a normal for loop when you just want to read the items. Notice the curly brackets around the loop body.

// Loop over every item in arrayOrCollection, one at a time.
// Each time round, the current item is copied into variable,
// then the loop body runs. It stops after the last item.
for (dataType variable : arrayOrCollection) {
    // loop body: code that uses 'variable'
}
The enhanced for loop. for (String place : placeList) { ... } reads as “for each String place in placeList, run the body”. The round brackets hold three things: the type of each item (String), a new variable name for the current item (place), and, after the colon, the array (placeList). The body goes in curly brackets.
Show me the Python version
placeList = ["World", "Europe", "UK", "Brighton"]
for place in placeList:
    print("Hello " + place)

This is Python’s normal for ... in ... loop. Java writes a colon : where Python writes in, puts the type in front of the loop variable, and uses { } instead of a colon and indentation.

HelloPlaces

HelloPlaces does exactly what HelloBrighton did, but with only one println. It brings in three new things: a list of places (an array), names for data (variables: placeList and place), and a for-each loop.

public class HelloPlaces
{
    public void run()
    {
        // Make an array of 4 place names and keep it in placeList.
        String[] placeList = {"World", "Europe", "UK", "Brighton"};

        // Loop: run the body once for each String in placeList,
        // copying it into place first. Stops after "Brighton".
        for (String place: placeList)
        {
            // Join "Hello " and the current place, and print it.
            System.out.println("Hello " + place);
        }
    }

    // Java starts here and calls run().
    public static void main(String[] args) {
        new HelloPlaces().run();
    }
}
  • Line 1 of run(): declares placeList as an array of Strings and fills it with four places. Notice the curly brackets, the commas, and the semicolon at the end.
  • The loop: makes a new variable place, looks in placeList, and for each string copies it into place and runs the body.
  • The body: prints "Hello " + place. place changes each time round, so each line is different.
+ with Strings. "Hello " + place joins two Strings into one. If place holds "UK" the result is "Hello UK". Note the space inside "Hello "; without it you get HelloUK.
Show me the Python version
place = "UK"
print("Hello " + place)   # Hello UK

Same as Python. One extra: Java also lets you join a String and a number with + (for example "Rating " + 3); Python would need str(3).

Running it is “a complete anti-climax”: same output as HelloBrighton. But give the array 10 places and it prints all 10, still with one println, and changing “Hello” to “Bonjour” is one edit.

Click through Tracer 1 to watch the loop run.

8. Making choices: the if statement

So far: sequences of instructions, and loops that run the same instructions again. Now: choosing which instructions to run. The simplest way is an if statement. Another way is a switch statement.

// If the test is true, run the first block;
// otherwise run the else block (the else part is optional).
if (test) {
    // true code block: runs if the test is true
} else {
    // false code block: runs if the test is false
}
if and else. Start with the word if, then a test in round brackets. The instructions to run when the test is true go in curly brackets. The else part is optional: its block runs when the test is false. After the if, the program carries on with the next line. Think of a fork in the road.
Show me the Python version
if test:
    # runs if the test is true
    ...
else:
    # runs if the test is false
    ...

Same idea as Python. Java puts the test in round brackets, uses { } instead of a colon and indentation, and has no colon after else.

The test

The test is something that is either true or false. The simplest test asks whether two things are the same. Testing fixed values (2 == 2) is pointless because we already know the answer. Tests are useful when a value comes from a variable, like age == 18 or whether place is “Brighton”.

== versus .equals. For numbers, test sameness with two equals signs: age == 18. (One = means “put a value in a box”; two == means “are these the same?”.) For Strings, use .equals: place.equals(home) is true if the two Strings have the same letters. Do not use == for Strings: it checks whether they are the very same object in memory, and can say false even when the letters match. The slides call this “the slightly strange way” and say more comes later.
Show me the Python version
age = 18
print(age == 18)        # True

place = "Brighton"
home = "Brighton"
print(place == home)    # True: Python == compares the letters

In Python, == works for numbers and text. In Java, == is for numbers, and .equals(...) is for Strings. Mixing this up is a very common Java mistake.

HomeTown: an if inside the loop

HomeTown is HelloPlaces with a new list, a new variable home set to "Brighton", and an if statement inside the loop. It says hello to every place, and when it reaches Brighton it prints a second message.

public class HomeTown
{
    public void run()
    {
        // The places to say hello to.
        String[] placeList = {"London", "Paris", "Brighton", "New York"};
        // A new variable: our home town.
        String home = "Brighton";

        // Loop: once for each place, stopping after "New York".
        for (String place: placeList)
        {
            // Say hello to every place.
            System.out.println("Hello " + place);

            // If: the extra message runs ONLY when place is the
            // same text as home. Otherwise nothing extra happens.
            if (place.equals(home)) {
                // print: no new line, so the next text joins on.
                System.out.print("there's no place like home, ");
                // println: finish the line.
                System.out.println("my favourite place is " + place);
            }
        }
    }

    // Java starts here and calls run().
    public static void main(String[] args) {
        new HomeTown().run();
    }
}

You can add new variables wherever you need them. Their names should start with a small letter and must not clash with anything else.

print versus println. System.out.println(...) prints and then moves to a new line. System.out.print(...) prints and stays on the same line, so the next thing printed joins on. HomeTown uses print then println to build one line from two pieces.
Show me the Python version
print("there's no place like home, ", end="")   # stay on this line
print("my favourite place is Brighton")         # then finish it

Java println = a normal Python print. Java print = Python print(..., end="").

Click through Tracer 2 to watch the test come out false, false, true, false.

9. Combining statements, and chained ifs

In Java, a for loop and an if statement each count as one instruction that can hold a block of other instructions. So you can put them inside each other: an if inside a for, a for inside an if, several ifs inside an else, and so on. The key is correct nesting: the curly brackets group the instructions. BlueJ helps by indenting the inner block and colouring its background.

Chained if: else if

// Check test1, then test2, then test3, in order.
// The FIRST block whose test is true runs; the rest are skipped.
// If none is true, the final else block runs.
if (test1) {
    // code block 1: runs if test1 is true
} else if (test2) {
    // code block 2: runs if test2 is true
} else if (test3) {
    // code block 3: runs if test3 is true
} else {
    // code block 4: runs if all the tests are false
}
else if. Checks several tests one after another. Java runs the block for the first test that is true and skips the rest. You can have as many else if parts as you need, and an optional final else for “none of the above”.
Show me the Python version
if test1:
    ...
elif test2:
    ...
elif test3:
    ...
else:
    ...

Java else if = Python elif. Same order of checking, same “first true one wins” rule.

EstateAgent

EstateAgent goes through an array of rooms, {"hall", "kitchen", "lounge", "kitchen", "bedroom", "hall"}, and uses a chain of ifs to make a different comment for each kind of room. Here is the loop:

// Loop: once for each room in rooms, stopping after the last one.
for (String room: rooms){
    // print, not println, so the comment stays on the same line.
    System.out.print("Here we are in the "+ room + ". ");

    // If / else if / else chain: only the first matching
    // room's comment runs. Any other room gets the else.
    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 if (room.equals("lounge")) {
        System.out.print("Notice the original fireplace.");
    } else if(room.equals("hall")) {
        System.out.print("Nice and big windows.");
    } else {
        System.out.print("What is this room used for?");
    }

    // An empty println just finishes the line.
    System.out.println();
}

It works, but every test looks the same: “is room this? is room that?”. Imagine following 100 of them. When you check one variable against many possible values, there is a cleaner way: switch.

10. The switch statement

// Look at the value of expression and jump to the case
// with the same value. break leaves the switch.
// If no case matches, default runs.
switch (expression) {
    case value1:
        // instructions for value1
        break;
    case value2:
        // instructions for value2
        break;
    default:
        // instructions when no case matches
}
switch, case and default. A switch is like an if, but the round brackets hold a value (usually a number or a String), not a true/false test. The body is a set of cases. Each case is labelled with one possible value, followed by a colon :. Java jumps to the case whose label matches and runs its instructions. default: is optional, like a final else: it runs when nothing matches. Notice there are no curly brackets around each case’s instructions.
Show me the Python version
match room:                  # Python 3.10 and newer
    case "kitchen":
        print("Can you smell the coffee? ", end="")
    case "bedroom":
        print("Plenty of room for all your clothes.", end="")
    case _:                  # like default
        print("What is this room used for?", end="")

Python’s match (or an if/elif chain) does the same job. Big difference: a Python case never runs into the next case, but a Java case does unless you write break.

break. The cases are not sealed off from each other. Without a break, Java carries on into the next case’s instructions (“fall-through”). break; means “I’m done here; jump out of the switch to the next instruction after it”. The break in the last case (usually default) is optional, because there is nothing after it to fall into. break can also end a loop early; that comes later.
Show me the Python version
# Python has no fall-through, so it needs no break in match.
# Python's break is only for leaving a loop early:
for place in ["UK", "Brighton"]:
    if place == "Brighton":
        break

In Java you almost always end each case with break;. Python’s match does this for you automatically.

EstateAgent with a switch

// Switch on room: jump to the matching case, run its line,
// then break out. Any room not listed runs default.
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:
        System.out.print("What is this room used for?");
}

This is your lab exercise (Ex_EstateAgent_Switch). Click through Tracer 3 to see it run.

Month lengths: cases that share code

Several cases can share one block. Here april, june, september and november have no instructions of their own, so they fall through to “30 days”. break stops the fall-through. default handles every other month (and anything that is not a month name).

// Switch on month. april, june, september and november have
// no code of their own, so they fall through to the shared
// "30 days" line. february has its own line. Anything else
// (including words that are not months) runs default.
switch (month) {
    case "april":
    case "june":
    case "september":
    case "november":
        System.out.println("30 days");
        break;

    case "february":
        System.out.println("28 days");
        break;

    default:
        System.out.println("31 days");
}

Optional challenge: stars without break

StarRating shows a rating as stars (★), from 1 to 5, and uses fall-through on purpose: rating 3 starts at case 3 and falls through cases 2 and 1, giving ★★★. Rating 5 falls through all of them. The break at case 1 stops it. The challenge: how would you write it with a break after every case and the same output? (The answer is at the bottom of StarRating.java.)

// Switch with NO break until case 1: Java jumps in at the
// matching rating and falls through every case below it,
// printing one star per case. break at case 1 stops it.
// Anything that is not 1 to 5 jumps to default.
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; // stop at the end
    default:
        System.out.print("Invalid rating");
}

Notice the case labels here are numbers (case 5:), not text, because rating is an int. Click through Tracer 4.

Switch rules and limits

  • Allowed case values: whole numbers (int, and the smaller byte and short), characters (char, like 'A'), Strings, and enums (advanced, ignore for now).
  • Not allowed: long, float, double, boolean, and other object types.
  • A switch cannot compare with <, >, <=, >=. It only checks “equal to”.
  • Rule of thumb: use switch to compare one value against several fixed options; use if-else for ranges and “bigger than” tests.

11. Summary: key ideas

  • Sequence, selection, iteration: the three core structures. With just these you can build almost any program.
  • Variables: named boxes holding values. Arrays: a group of values of one type.
  • Code blocks: curly brackets group instructions; blocks can be nested.
  • Enhanced for loop: repeat instructions for each item in an array.
  • If statements make choices, using tests that are true or false; else and else if add more branches.
  • Switch: a compact way to test one value against many options. break ends a switch (or loop) early.
  • Keywords such as for, if, else, switch, case, break are reserved words in Java: you cannot use them as variable names.

Sections 5–11 follow the main lecture slides in order.

Click-through tracers

Press Next step. The highlighted line is the one Java is running. Watch the variables and the terminal change. Grey-green lines are comments; Java skips them.

Tracer 1: HelloPlaces (an enhanced for loop)

1public class HelloPlaces
2{
3 // run() holds the program's instructions.
4 public void run()
5 {
6 // Make an array of 4 Strings, kept in placeList.
7 String[] placeList = {"World", "Europe", "UK", "Brighton"};
8
9 // Loop: once for each String in placeList, copied
10 // into place each time. Stops after "Brighton".
11 for (String place: placeList)
12 {
13 // Join "Hello " and place, print, new line.
14 System.out.println("Hello " + place);
15 }
16 }
17
18 // Java starts here: make the object, call run().
19 public static void main(String[] args) {
20 new HelloPlaces().run();
21 }
22}
Variables
Terminal (what you see)

Tracer 2: HomeTown (an if inside the loop)

1// The places to say hello to.
2String[] placeList = {"London", "Paris", "Brighton", "New York"};
3// Our home town.
4String home = "Brighton";
5
6// Loop: once for each place; stops after "New York".
7for (String place: placeList)
8{
9 // Say hello to the current place.
10 System.out.println("Hello " + place);
11 // If: only when place has the same letters as home.
12 if (place.equals(home)) {
13 // print: stay on the same line.
14 System.out.print("there's no place like home, ");
15 // println: finish the line.
16 System.out.println("my favourite place is " + place);
17 }
18}
Variables
Terminal (what you see)

Tracer 3: EstateAgent with a switch

1// The rooms on the tour.
2String[] rooms = {"hall", "kitchen", "lounge", "kitchen", "bedroom", "hall"};
3
4// Loop: once for each room; stops after the last "hall".
5for (String room: rooms){
6 // print: room and comment share one line.
7 System.out.print("Here we are in the " + room + ". ");
8
9 // Switch: jump to the case matching room, run it,
10 // then break out. Other rooms run default.
11 switch (room) {
12 case "kitchen":
13 System.out.print("Can you smell the coffee? ");
14 break;
15 case "bedroom":
16 System.out.print("Plenty of room for all your clothes.");
17 break;
18 case "lounge":
19 System.out.print("Notice the original fireplace.");
20 break;
21 case "hall":
22 System.out.print("Nice and big windows.");
23 break;
24 default:
25 System.out.print("What is this room used for?");
26 }
27
28 // Finish the line.
29 System.out.println();
30}
Variables
Terminal (what you see)

Tracer 4: StarRating (switch without break)

1// An array of three whole numbers.
2int[] ratings = {1, 3, 5};
3// Loop: once for each rating; stops after 5.
4for (int rating : ratings){
5 // Label for this rating, same line.
6 System.out.print("Rating " + rating + ": ");
7 // Switch with fall-through: jump in at the
8 // matching case, then run every case below it,
9 // until the break after case 1.
10 switch (rating){
11 case 5: System.out.print("★");
12 case 4: System.out.print("★");
13 case 3: System.out.print("★");
14 case 2: System.out.print("★");
15 case 1: System.out.print("★");
16 break; // stop at the end
17 default:
18 System.out.print("Invalid rating");
19 }
20 // End the line.
21 System.out.println();
22}
Variables
Terminal (what you see)

What will it print?

Guess first. Write your guess down. Then open the answer.

1. A loop with print and println.

// An array of two Strings.
String[] pets = {"cat", "dog"};
// Loop: once for each pet, stopping after the last one.
for (String pet : pets) {
    // print the pet and a space, staying on the same line
    System.out.print(pet + " ");
}
// After the loop: print a word and end the line
System.out.println("done");
Reveal answer

cat dog done – all on one line. Inside the loop, print never starts a new line. Only the final println ends the line.

2. A chained if.

// A String variable holding a place.
String place = "Hove";
// Chained if: Java checks each test in order and runs
// only the first block whose test is true.
if (place.equals("Brighton")) {
    System.out.println("Home!");
} else if (place.equals("Hove")) {
    System.out.println("Next door to home");
} else {
    System.out.println("Somewhere else");
}
Reveal answer

Next door to home. The first test is false, the second is true, so that block runs and the else is skipped.

3. The month switch from the lecture. What does it print when month is "june"? And when it is "march"?

// Switch on month: four months share one line,
// february has its own, everything else runs default.
switch (month) {
    case "april":
    case "june":
    case "september":
    case "november":
        System.out.println("30 days");
        break;
    case "february":
        System.out.println("28 days");
        break;
    default:
        System.out.println("31 days");
}
Reveal answer

"june" → 30 days. Java jumps to case "june", falls through to the shared println, and then break stops it.

"march" → 31 days. No case says "march", so default runs.

4. Spot the missing break.

// room holds "kitchen".
String room = "kitchen";
// Switch on room. Look carefully at where the breaks are.
switch (room) {
    case "kitchen":
        System.out.println("Can you smell the coffee?");
    case "bedroom":
        System.out.println("Plenty of room for all your clothes.");
        break;
    default:
        System.out.println("What is this room used for?");
}
Reveal answer

Two lines:

Can you smell the coffee?
Plenty of room for all your clothes.

The kitchen case has no break, so Java falls through into the bedroom case too. The break there stops it before default.

The lab: what you will do

The lab instructions are at the end of the main lecture slides (slide 46). Your Lab Walkthrough page takes you through them click by click.

  1. Download the project. Get enhanceForChoices.zip and open it in BlueJ (Project → Open ZIP/JAR…).
  2. Explore the example classes. Double-click each one to read the code: HelloWorld, HelloBrighton, HelloPlaces, HomeTown, EstateAgent (and StarRating). Compile and run each to check you understand it.
  3. Work on the exercises (classes starting with Ex_). Follow the instructions at the top of each file:
    • Ex_HomeTown – add an else so places that are not home say “I’ve never been there”; then add an else if to give an opinion on London.
    • Ex_EstateAgent_Switch – rewrite EstateAgent using a switch statement.
    • Ex_IfLoop_NurseryRhyme (optional) – rewrite the “10 Green Bottles” program with a loop and if statements.
  4. Check solutions (optional). Model answers start with Sol_. Only look after you have tried.
  5. Challenging exercise (for experienced students): Star Ratings. Change StarRating to use two arrays (hotel names and ratings) and print each hotel with its stars, using a switch without breaks. The file is called Ex_StartRating_Challenging.

Need help with BlueJ? Section 2 above, or the Using BlueJ slides.

Quiz: 8 questions

Click an answer. You find out straight away. Your answers are saved in this browser.

Score: 0 / 8

Q1. What does compile mean?

Q2. In BlueJ, how do you run a compiled class the standard way?

Q3. What ends almost every Java instruction?

Q4. How do you test whether the String place is the same as home?

Q5. What is String[] cities = {"London", "York"};?

Q6. placeList holds 4 places. How many times does for (String place : placeList) { ... } run its body?

Q7. In a switch, what does break; do?

Q8. Which job can a switch not do?

Optional reading: Programming and Java background, and Java on your own PC

This is from the optional Programming and Java – Additional Background and Getting Started slides. You do not need to master it before starting the practical work. The university lab PCs already have everything installed.

Background in one minute

Setting up Java on your own PC

Try your first program in BlueJ (from the slides)

  1. Project → New Project, name it (e.g. myProject), choose a place, OK.
  2. New Class → name it HelloWorld → Class → OK.
  3. Double-click the box, replace the code with the code below.
  4. Click Compile. Then right-click the box → void main(String[] args) → OK.
// The class HelloWorld holds the whole program.
public class HelloWorld {
    // main: where Java starts running.
    public static void main(String[] args) {
        // Print Hello, World! and move to a new line.
        System.out.println("Hello, World!");
    }   // end of main
}   // end of the class

You should see Hello, World! in the terminal window.

CI401 Week 1 · Sunday prep · made from the Week 1 slides and the enhanceForChoices lab files.