Conditions and Branching in Java
if-else
if (marks >= 90) {
System.out.println("A");
} else if (marks >= 75) {
System.out.println("B");
} else if (marks >= 60) {
System.out.println("C");
} else {
System.out.println("Fail");
}
Switch
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Modern method
int day = 2;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Invalid";
};
System.out.println(name);
String type = switch (day) {
case 1, 2, 3 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
Advantages
- No
break required.
- No accidental fall-through.
- Can directly return/produce a value.
- Multiple values can be grouped.
yield in Switch
String result = switch (day) {
case 1 -> {
System.out.println("Processing...");
yield "Monday";
}
default -> "Other";
};
return → returns from the method
yield → returns a value from the switch expression