Conditions and Loops
if / else
Control flow means deciding which lines run and how many times. By default Java runs statements top to bottom; if, switch and loops change that order. Almost every program combines these: "for each order, if it's paid, ship it, otherwise send a reminder".
An if condition must be a boolean - true or false. Combine conditions with && (and), || (or) and ! (not).
switch
switch is a cleaner way to compare one value against many fixed options (days, menu choices, order statuses). Each case is one option, and default handles anything else. It works with numbers, characters, Strings and enums.
String day = "SUN";
switch (day) {
case "SAT":
case "SUN":
System.out.println("Weekend sale");
break;
default:
System.out.println("Normal prices");
}Loops
Java has three main loops. for is best when you're counting ("repeat 10 times"). The enhanced for loop for (String item : cart) goes through every item in an array or list. while repeats as long as a condition is true, for when you don't know the number of rounds in advance. break leaves a loop early; continue skips to the next round.
for (int i = 1; i <= 3; i++) {
System.out.println("Item " + i);
}
int stock = 3;
while (stock > 0) {
stock--;
}
String[] items = {"Pen", "Book", "Bag"};
for (String it : items) { // enhanced for loop
System.out.println(it);
}break in a switch. Without it, the code carries on into the next case.if/elsechoose between paths using a boolean condition.switchcompares one value with many cases - rememberbreak.for, enhancedforandwhilerepeat code.
