if, else if and else choose what runs; combine conditions with &&, || and !. The ternary condition ? a : b picks between two values.
Modern Java has switch expressions: case "A" -> "Excellent"; with arrows, no fall-through and a value you can assign. Use default to cover everything else.
Loops: the classic for (int i = 0; i < n; i++), the enhanced for (int s : scores) for every item, while for repeating until a condition changes, and do...while when the body must run at least once. break exits a loop; continue skips to the next round.
public class Grades {
static String gradeFor(int score) {
if (score >= 75) return "A";
else if (score >= 65) return "B";
else if (score >= 45) return "C";
else if (score >= 30) return "D";
else return "F";
}
static String remarkFor(String grade) {
return switch (grade) {
case "A" -> "Excellent";
case "B" -> "Very good";
case "C" -> "Good";
case "D" -> "Satisfactory";
default -> "Fail";
};
}
public static void main(String[] args) {
int[] scores = {82, 67, 49, 31, 18};
for (int score : scores) {
String grade = gradeFor(score);
System.out.println(score + " -> " + grade + " (" + remarkFor(grade) + ")");
}
for (int i = 0; i < scores.length; i++) {
String status = scores[i] >= 30 ? "pass" : "fail";
System.out.println("Student " + (i + 1) + ": " + status);
}
for (int n = 1; n <= 15; n++) {
if (n % 15 == 0) System.out.print("FizzBuzz ");
else if (n % 3 == 0) System.out.print("Fizz ");
else if (n % 5 == 0) System.out.print("Buzz ");
else System.out.print(n + " ");
}
System.out.println();
int countdown = 3;
while (countdown > 0) {
System.out.println("Starting in " + countdown + "...");
countdown--;
}
}
}Key points
- Prefer switch expressions with
->: no fall-through, and they return a value. - Enhanced
forfor every item; indexedforwhen you need positions. - Keep conditions simple — return early from methods instead of nesting.
Exercise
Print the multiplication table (1–12) for a number given as a command-line argument. Then write a program that keeps doubling an investment of 100,000 TSh at 12% per year with a while loop until it exceeds 1,000,000, printing each year.
Show solution
Try the exercise yourself first — then compare your approach with this one.
The table loops from 1 to 12, reading the number from the first argument. The investment loop repeats while the balance is still at or below one million, growing it by 12% and counting years.
public class Loops {
public static void main(String[] args) {
int number = args.length > 0 ? Integer.parseInt(args[0]) : 7;
for (int i = 1; i <= 12; i++) {
System.out.printf("%2d x %d = %d%n", i, number, i * number);
}
double balance = 100_000;
int year = 0;
while (balance <= 1_000_000) {
balance *= 1.12;
year++;
System.out.printf("Year %2d: %,.0f TSh%n", year, balance);
}
System.out.println("It takes " + year + " years to pass 1,000,000 TSh.");
}
}