Sub topic 2
Making Decisions: Control Flow Statements
This chapter assumes you have read the earlier chapters on variables and operators.
Control flow means choosing which lines of code run, and how many times. Java uses statements like if and for to control this.
Deciding with if/else
An if statement runs code only when a condition is true. An else block runs when it is false.
int score = 75;
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Try again");
}Loops: Repeating Work
A loop repeats a block of code. A for loop is the most common. It has three parts: a start value, a condition to keep going, and a step.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}A while loop repeats as long as its condition stays true.
Working with Arrays
An array stores several values of the same type in one variable. You reach each value by its index, its numbered position starting at 0.
int[] numbers = {10, 20, 30};
for (int n : numbers) {
System.out.println(n);
}The for loop above is a shortcut: it runs once for each value in the array.
Strings and String Manipulation
A String is text. Strings are objects, so they come with ready-made methods (built-in actions).
String name = "Java";
System.out.println(name.length()); // 4
System.out.println(name.toUpperCase()); // JAVACalling a method looks like name.method(). The method runs and gives back a result.
Putting It Together
String[] pets = {"cat", "dog", "bird"};
for (String pet : pets) {
if (pet.equals("dog")) {
System.out.println("Found the dog!");
}
}This loops through the array, and for each value decides whether it equals "dog". Note we use .equals() to compare text, not ==.
Exercise
How many times will this loop run? for (int i = 0; i < 3; i++) { }
Show answer
Three times. i starts at 0, then becomes 1, then 2. When i is 3, the condition i < 3 is false and the loop stops.