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.
if runs code when the condition is true.else runs alternative code when the preceding condition is false.else if lets you check additional conditions in sequence.switch 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.
for is most often used when the number of repetitions is known.while repeats actions while the condition remains true.do while 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
When using while you must ensure that its condition eventually becomes false or that the loop is stopped.