Control flow: if, switch expressions and loops
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
Choosing a path
Programs make decisions and repeat work. This lesson covers the tools for both. If you know another language, most of it will look familiar. Pay attention to the switch expression, which is one of the best improvements in modern Java.
if, else if, else
An if needs a condition of type boolean. Java does not accept numbers or strings as conditions, so if (count) is an error. Use braces even for one-line bodies. Skipping them is a classic source of bugs when somebody adds a second line later.
switch expressions
The old switch statement needed break at the end of every case and fell through when you forgot it. Since Java 14 you can write a switch expression with arrows. It produces a value, it does not fall through, and the compiler checks that all cases are covered.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// if / else if
int score = 72;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 75) {
System.out.println("Grade B");
} else if (score >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
// switch expression with arrows and multiple labels
String day = "SATURDAY";
String type = switch (day) {
case "SATURDAY", "SUNDAY" -> "weekend";
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "weekday";
default -> throw new IllegalArgumentException("Unknown day: " + day);
};
System.out.println(day + " is a " + type);
// switch with a block and yield
int month = 2;
int days = switch (month) {
case 2 -> {
boolean leap = false;
yield leap ? 29 : 28;
}
case 4, 6, 9, 11 -> 30;
default -> 31;
};
System.out.println("Days: " + days);
// for loop: a multiplication table
for (int i = 1; i <= 5; i++) {
System.out.printf("7 x %d = %d%n", i, 7 * i);
}
// while loop: halve until small
double value = 100;
int steps = 0;
while (value > 1) {
value /= 2;
steps++;
}
System.out.println("Steps: " + steps);
// do-while runs at least once
int attempts = 0;
do {
attempts++;
} while (attempts < 3);
System.out.println("Attempts: " + attempts);
// enhanced for loop
String[] fruits = {"mango", "apple", "guava"};
for (String fruit : fruits) {
System.out.println("I like " + fruit);
}
// break and continue: first 5 primes
List<Integer> primes = new ArrayList<>();
for (int n = 2; primes.size() < 5; n++) {
boolean isPrime = true;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
isPrime = false;
break;
}
}
if (!isPrime) {
continue;
}
primes.add(n);
}
System.out.println(primes);
// A labelled break leaves both loops
search:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
if (row * col == 6) {
System.out.println("Found at " + row + "," + col);
break search;
}
}
}
}
}
Walking through it
The first switch uses string cases. Several labels share one result with commas. Because it is an expression, we assign it to type directly. With default throwing an exception, we never end up with an unset value. When you switch on an enum or a sealed type and cover every case, you can leave out default, and the compiler will tell you if a case is missing. That check is why I prefer switch expressions to long if chains.
The second switch shows a block with yield. When a case needs more than one expression, wrap it in braces and use yield to give back the value. (In real code, the leap-year check would use a calculation.)
The for loop has three parts: initialisation, condition, update. i++ adds one after each pass. The while loop checks first, so it may run zero times. The do-while loop checks at the end, so it runs at least once. Both of those are chosen when you do not know in advance how many rounds you need.
The enhanced for loop reads as "for each fruit in fruits". It works on arrays and on any collection. It has no index to get wrong, so use it whenever you do not need the position.
The prime search combines break and continue. break leaves the inner loop as soon as a divisor is found. continue skips the rest of the current pass of the outer loop. The loop condition primes.size() < 5 keeps going until we have five. A label on a loop, such as search:, lets break search leave an outer loop from inside an inner one. Use labels rarely. Often a method with return is clearer.
Reading input
To read from the keyboard, use Scanner: Scanner in = new Scanner(System.in); and then in.nextLine() for text or in.nextInt() for a number. Remember that nextInt leaves the line break in the input, so call nextLine() once afterwards before reading text. Better still, read every line with nextLine() and convert it with Integer.parseInt, which throws NumberFormatException on bad input. You will handle that in the exceptions lesson.
Common mistakes
- Using
=in a condition.if (x = 5)does not compile for ints, butif (flag = true)does and assigns. - A semicolon right after the
iforforbrackets. It becomes an empty body. - Off-by-one errors in loop limits. Check the first and last pass on paper.
- Forgetting
breakin an old-style switch. Arrow syntax avoids it. - Infinite loops. Make sure something in the loop moves the condition toward false.
Try it yourself
- Print the numbers 1 to 30, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5 and "FizzBuzz" for both.
- Write a switch expression that converts a number from 1 to 7 into a day name and throws an exception for other values.
- Use a
Scannerto build a guessing game with a secret number and "higher" or "lower" hints.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// if / else if
int score = 72;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 75) {
System.out.println("Grade B");
} else if (score >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
// switch expression with arrows and multiple labels
String day = "SATURDAY";
String type = switch (day) {
case "SATURDAY", "SUNDAY" -> "weekend";
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "weekday";
default -> throw new IllegalArgumentException("Unknown day: " + day);
};
System.out.println(day + " is a " + type);
// switch with a block and yield
int month = 2;
int days = switch (month) {
case 2 -> {
boolean leap = false;
yield leap ? 29 : 28;
}
case 4, 6, 9, 11 -> 30;
default -> 31;
};
System.out.println("Days: " + days);
// for loop: a multiplication table
for (int i = 1; i <= 5; i++) {
System.out.printf("7 x %d = %d%n", i, 7 * i);
}
// while loop: halve until small
double value = 100;
int steps = 0;
while (value > 1) {
value /= 2;
steps++;
}
System.out.println("Steps: " + steps);
// do-while runs at least once
int attempts = 0;
do {
attempts++;
} while (attempts < 3);
System.out.println("Attempts: " + attempts);
// enhanced for loop
String[] fruits = {"mango", "apple", "guava"};
for (String fruit : fruits) {
System.out.println("I like " + fruit);
}
// break and continue: first 5 primes
List<Integer> primes = new ArrayList<>();
for (int n = 2; primes.size() < 5; n++) {
boolean isPrime = true;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
isPrime = false;
break;
}
}
if (!isPrime) {
continue;
}
primes.add(n);
}
System.out.println(primes);
// A labelled break leaves both loops
search:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
if (row * col == 6) {
System.out.println("Found at " + row + "," + col);
break search;
}
}
}
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account