Conditions and Loops
💻 JavaControl the flow of a program with if, switch, for and while.
Programs become useful when they make decisions and repeat work. Java gives you clear, predictable tools for both.
- Write if and else-if chains.
- Use switch expressions.
- Write for and while loops.
if and else
Conditions must be boolean. Java will not treat a number as true or false.
int score = 72;
if (score >= 70) {
System.out.println("A");
} else if (score >= 60) {
System.out.println("B");
} else {
System.out.println("Keep working");
}switch
Modern Java switch expressions return a value and use arrow syntax. They are clearer than long if chains on one variable.
String level = "SS2";
String stage = switch (level) {
case "SS1" -> "Junior";
case "SS2", "SS3" -> "Senior";
default -> "Unknown";
};
System.out.println(stage);Loops
Use for when you know how many times to repeat. Use while when you repeat until a condition changes.
for (int i = 1; i <= 5; i++) {
System.out.println("Week " + i);
}
int countdown = 3;
while (countdown > 0) {
System.out.println(countdown);
countdown--;
}Practice
- Print the grade for a score using if and else-if.
- Use a switch to map a day number to a day name.
- Print the numbers 1 to 20, but only the even ones.
Hands-on exercise
Write a program that prints the 7 times table from 1 to 12 in the form:
7 x 1 = 7
7 x 2 = 14
... using a for loop.
Recap
if chooses between branches, switch maps one value to one result, and loops repeat work.
Example
int score = 72;
if (score >= 70) {
System.out.println("A");
} else if (score >= 60) {
System.out.println("B");
} else {
System.out.println("Keep working");
}
Exercises
7 x 1 = 7
7 x 2 = 14
... using a for loop.
Expected Output
Twelve correctly formatted lines ending with 7 x 12 = 84.
Lesson Nav
Java Course
0/9 lessons completed
- 1 Getting Started with Java Tutorial
- 2 Variables and Data Types Tutorial
- 3 Conditions and Loops Tutorial
- 4 Methods and Parameters Tutorial
- 5 Arrays and ArrayLists Tutorial
- 6 Classes and Objects Tutorial
- 7 Inheritance, Interfaces and Polymorphism Tutorial
- 8 Exceptions and Files Tutorial
- 9 Project: A Console Grade Book Project