Operators and Control Flow
Conditionals
int score = 82;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 75) {
grade = "B";
} else {
grade = "C";
}
Loops
for (int i = 0; i < 5; i++) {
System.out.println("Lesson " + i);
}
int attempts = 0;
while (attempts < 3) {
attempts++;
}
The classic for (init; condition; update) form gives you full control over the loop counter, which is useful when you need the index itself, not just each item. When you just need to visit every item in a collection, Java also offers an enhanced for loop, covered in the arrays lesson.
The switch statement
switch (grade) {
case "A":
System.out.println("Excellent");
break;
case "B":
System.out.println("Good");
break;
default:
System.out.println("Keep going");
}
Forgetting break is one of the most common Java bugs — without it, execution “falls through” into the next case regardless of whether it matches, running code you didn’t intend to run. Modern Java (14 and later) also supports a newer arrow-style switch expression that avoids this pitfall entirely, but the traditional form above is still extremely common in existing code.
Operators
10 / 3 // 3 -- integer division truncates, doesn't round
10 / 3.0 // 3.3333... -- involving a double gives a decimal result
10 % 3 // 1 -- remainder
int x = 5;
x += 3; // 8 -- same as x = x + 3
Integer division between two int values always truncates toward zero rather than rounding — a very common source of bugs for anyone expecting decimal results. If you need a decimal result, at least one of the two operands needs to be a double or float.