Careeroza
Nested if
An if Inside Another if
Example
You can put an if inside another one when a second decision depends on the first.
public class Main {
public static void main(String[] args) {
boolean isLoggedIn = true;
boolean isAdmin = false;
if (isLoggedIn) {
System.out.println("Welcome back!");
if (isAdmin) {
System.out.println("Opening admin dashboard");
} else {
System.out.println("Opening user home page");
}
} else {
System.out.println("Please log in");
}
}
}Output
Welcome back! Opening user home page
Flatten When Possible
Deep nesting is hard to read. Combine conditions with && or return early.
Example
public class Main {
public static void main(String[] args) {
int year = 2024;
// leap year: divisible by 4, but not by 100 unless also by 400
boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
System.out.println(year + " leap year? " + leap);
System.out.println(1900 + " leap year? " + ((1900 % 4 == 0 && 1900 % 100 != 0) || 1900 % 400 == 0));
}
}Output
2024 leap year? true 1900 leap year? false