Control flow statements decide which code actually runs and how many times - the same core ideas as any language, with Java's particular syntax.
if / else if / else
int marks = 78;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else {
System.out.println("Grade C or below");
}
switch
A switch statement is a cleaner alternative when you are comparing one variable against several fixed values:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Some other day");
}
Do not forget break - without it, execution "falls through" into the next case, which is rarely what you want.
Loops
// for: when you know how many times to loop
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
// while: when you loop until a condition changes
int attempts = 0;
while (attempts < 3) {
System.out.println("Attempt " + attempts);
attempts++;
}
// do-while: like while, but always runs at least once
int input;
do {
input = getInput(); // pretend this reads user input
} while (input != 0);
break exits a loop immediately; continue skips to the next iteration without exiting.