Control flow
Control flow decides which code runs and how many times: if for decisions, switch for choosing between many options, and loops for repetition.
if, else if, else
public class Main {
public static void main(String[] args) {
int marks = 72;
String grade;
if (marks >= 90) {
grade = "A";
} else if (marks >= 75) {
grade = "B";
} else if (marks >= 50) {
grade = "C";
} else {
grade = "F";
}
System.out.println("Grade: " + grade);
}
}Grade: C
The condition goes in brackets, and must be a boolean. Java checks each condition in order and runs only the first block that's true.
Comparing and combining
| Operator | Meaning |
|---|---|
==, != |
Equal, not equal (for numbers, chars and booleans) |
<, <=, >, >= |
Comparisons |
&& |
AND: both true |
|| |
OR: at least one true |
! |
NOT |
public class Main {
public static void main(String[] args) {
int age = 25;
boolean hasTicket = true;
if (age >= 18 && hasTicket) {
System.out.println("Welcome!");
}
String status = age < 13 ? "child" : "adult"; // the ternary operator
System.out.println(status);
String a = "hello";
String b = new String("hello");
System.out.println(a == b); // compares references: are they the same object?
System.out.println(a.equals(b)); // compares the text: use this for strings!
}
}Welcome! adult false true
⚠️ Always compare strings with
.equals(), never==.==checks whether two variables point to the same object, which sometimes happens to be true and sometimes not: a nasty, intermittent bug.
switch
Modern Java (14+) has switch expressions with arrows: no fall-through bugs, and they return a value:
public class Main {
public static void main(String[] args) {
String day = "SAT";
String type = switch (day) {
case "SAT", "SUN" -> "Weekend";
case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";
default -> "Unknown";
};
System.out.println(day + " is a " + type);
int month = 2;
int days = switch (month) {
case 2 -> 28;
case 4, 6, 9, 11 -> 30;
default -> 31;
};
System.out.println("Month " + month + " has " + days + " days");
}
}SAT is a Weekend Month 2 has 28 days
You'll still see the older case X: … break; style in existing code. Forgetting a break there makes execution "fall through" into the next case, so prefer the arrow form.
while loops
public class Main {
public static void main(String[] args) {
double balance = 1000;
int years = 0;
while (balance < 2000) {
balance = balance * 1.07;
years++;
}
System.out.printf("Doubled after %d years: %.2f%n", years, balance);
}
}Doubled after 11 years: 2104.85
do … while runs the body at least once before checking: handy for menus and retry prompts.
for loops
The classic for loop has three parts: start; condition; step:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 10; i > 0; i -= 3) {
System.out.print(i + " ");
}
System.out.println();
// a multiplication table with nested loops
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.printf("%4d", row * col);
}
System.out.println();
}
}
}1 2 3 4 5 10 7 4 1 1 2 3 2 4 6 3 6 9
for-each
To visit every element of an array or collection, the enhanced for loop is simpler and safer:
public class Main {
public static void main(String[] args) {
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
System.out.println("I like " + fruit);
}
}
}I like apple I like banana I like cherry
break and continue
public class Main {
public static void main(String[] args) {
for (int n = 1; n <= 20; n++) {
if (n % 2 == 0) continue; // skip even numbers
if (n > 9) break; // stop completely
System.out.print(n + " ");
}
System.out.println();
int[] numbers = {3, 7, 11, 15, 22};
int found = -1;
for (int n : numbers) {
if (n % 5 == 0) {
found = n;
break;
}
}
System.out.println(found == -1 ? "No multiple of 5" : "First multiple of 5: " + found);
}
}1 3 5 7 9 First multiple of 5: 15
Reading input
Programs read keyboard input with a Scanner:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Your name: ");
String name = in.nextLine();
System.out.print("Your age: ");
int age = in.nextInt();
System.out.println("Hi " + name + ", next year you'll be " + (age + 1));
}
}When you run it and type Asha and 31, you see:
Your name: Asha
Your age: 31
Hi Asha, next year you'll be 32FizzBuzz
The classic interview warm-up, combining loops and conditions:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 15; i++) {
if (i % 15 == 0) System.out.println("FizzBuzz");
else if (i % 3 == 0) System.out.println("Fizz");
else if (i % 5 == 0) System.out.println("Buzz");
else System.out.println(i);
}
}
}1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Without braces, an if controls only the single next statement. That's fine for one-liners like this, but use braces for anything longer.
Practice
- Print all leap years between 1990 and 2030 (divisible by 4, except centuries not divisible by 400).
- Use a
whileloop to add up the digits of98765(hint:% 10and/ 10). - Write a switch expression that turns a number 1–7 into a day name.
1.How should you check whether two Strings have the same text?
2.What's the advantage of case "A" -> ... over case "A": ... break;?
3.How many times does for (int i = 0; i < 3; i++) run its body?