New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Java› Conditions and Loops

Conditions and Loops

💻 Java

Control the flow of a program with if, switch, for and while.

Lesson 3 of 9 Tutorial
0 of 9 completed

Programs become useful when they make decisions and repeat work. Java gives you clear, predictable tools for both.

By the end of this lesson you can:
  • 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--;
}
Tip Avoid changing the loop variable inside the body of a for loop. It makes the loop much harder to reason about.

Practice

  1. Print the grade for a score using if and else-if.
  2. Use a switch to map a day number to a day name.
  3. 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

Exercise 1. Times table Easy
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.
Java exercise-1.java
Expected Output
Twelve correctly formatted lines ending with 7 x 12 = 84.

Lesson Nav

Lesson sections