Java · Lesson 3 of 6
Control Flow
if/else, for, while, and enhanced for-each loops.
- Beginner
- 15 min read
- 3 objectives
Before this lessonLesson 2: Variables and Types
What you will learn
- Write if/else chains
- Use for and while
- Iterate arrays with for-each
Control flow decides which code runs and how many times. Java's syntax will feel familiar if you know any C-style language: conditions go in parentheses and blocks go in braces. Unlike Python, indentation is only for humans; the braces are what the compiler reads.
Decisions and repetition
Control flow is how a program chooses what to do next and how it repeats work. Java uses the same building blocks as most languages: if/else to decide, switch to pick among many fixed options, and for/while loops to repeat. Blocks are wrapped in curly braces (indentation is only for humans), so a missing brace is a classic beginner error.
if / else
int score = 87;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}
System.out.println(grade);B
Conditions must be real boolean expressions; Java has no "truthy" values, so if (count) will not compile. Combine conditions with && (and), || (or) and ! (not). For a simple choice, the ternary operator is compact: String s = ok ? "yes" : "no";.
switch
When one value selects between many branches, switch is clearer than a chain of else if. Modern Java (14+) supports arrow syntax with no fall-through and can produce a value.
int day = 3;
String name = switch (day) {
case 1 -> "Mon";
case 2 -> "Tue";
case 3 -> "Wed";
default -> "Other";
};
System.out.println(name);Wed
Loops
A classic for loop has three parts: initialize, test and update. The enhanced for ("for-each") loop reads every element of an array or collection without an index. while repeats while a condition holds, and do/while runs the body at least once.
for (int i = 0; i < 3; i++) {
System.out.println("tick " + i);
}
int[] nums = {4, 8, 15};
int sum = 0;
for (int n : nums) {
sum += n;
}
System.out.println(sum);
int count = 3;
while (count > 0) {
count--;
}tick 0 tick 1 tick 2 27
Use break to exit a loop early and continue to jump to the next iteration.
if / else if / else, traced
public class Main {
public static void main(String[] args) {
int score = 78;
if (score >= 90) {
System.out.println("A");
} else if (score >= 75) {
System.out.println("B");
} else {
System.out.println("C");
}
boolean passed = score >= 50 && score <= 100;
System.out.println("passed = " + passed);
}
}B passed = true
The classic loops
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("round " + i);
}
int n = 3;
while (n > 0) {
System.out.println("countdown " + n);
n--;
}
String[] names = {"Ada", "Linus", "Grace"};
for (String name : names) {
System.out.println("Hi " + name);
}
}
}round 1 round 2 round 3 countdown 3 countdown 2 countdown 1 Hi Ada Hi Linus Hi Grace
A for loop has three parts in its parentheses: start (int i = 1), keep-going test (i <= 3) and step (i++). The enhanced for loop at the end reads as "for each name in names" and is the cleanest way to walk an array or list.
switch for many fixed choices
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);
}
}SAT is a weekend
Worked example: sum and average
public class Main {
public static void main(String[] args) {
int[] scores = {72, 88, 95, 61};
int sum = 0;
for (int s : scores) {
sum += s;
}
double average = (double) sum / scores.length;
System.out.println("sum = " + sum);
System.out.println("average = " + average);
}
}sum = 316 average = 79.0
Common mistakes
- Using
=instead of==in a condition. Java usually catches this for non-booleans, but not for boolean variables. - Off-by-one errors:
i <= nums.lengthreads one past the end and throwsArrayIndexOutOfBoundsException. - A stray semicolon after
if (x);makes the block run unconditionally. - Forgetting to change the loop variable in
while, causing an infinite loop.
Key takeaways
if/else if/elsedecide; conditions must beboolean.for, enhancedforandwhilerepeat work; watch off-by-one errors.- Modern
switchwith->is a compact way to map values to results. - Always use braces, even for one-line bodies.
// Write your solution here
