CONTROL FLOW

Java conditions and loops

Conditions let a program choose which code to run, while loops repeat actions. These constructs control the flow of a program and help create solutions that respond to data.

What are conditions?

Conditional statements evaluate a Boolean expression whose result is true or false, then use it to choose which branch of code to run.

  • runs code when the condition is true.
  • runs alternative code when the preceding condition is false.
  • lets you check additional conditions in sequence.
  • is useful for choosing an action from several distinct values.
int temperatura = 18;

if (temperatura >= 20) {
    System.out.println("Šilta");
} else if (temperatura >= 10) {
    System.out.println("Vėsu");
} else {
    System.out.println("Šalta");
}

Conditions are checked from top to bottom. Once the first matching branch runs, the remaining branches in this block are skipped.

What are loops?

A loop repeats a block of code while a condition holds or for a predetermined number of times. This avoids copying the same code.

  • is most often used when the number of repetitions is known.
  • repeats actions while the condition remains true.
  • runs the code first, then checks the condition.
for (int i = 1; i <= 3; i++) {
    System.out.println("Žingsnis " + i);
}
int energija = 3;

while (energija > 0) {
    System.out.println("Energijos liko: " + energija);
    energija--;
}

Controlling a loop

The keyword ends the loop, while skips the rest of the current iteration and moves on to the next one. Use them sparingly to keep the program flow clear.

Watch out for infinite loops.

When using while you must ensure that its condition eventually becomes false or that the loop is stopped.