Java if-else Statement
In this page:
Standard If-Else
if-else guarantees exactly one of its two blocks runs: the if-block when the condition is true, or the else-block as a fallback whenever it's false -- there's no case where neither or both execute.
Example: Standard If-Else
public class Main {
public static void main(String[] args) {
int age = 15;
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor"); // exactly one of these always runs
}
}
}
Login to try C/C++/Java/PHP code in the editor
Conditional Assignments
Rather than an empty variable followed by a separate if-else block to fill it in, you can compute and assign a value directly inside each branch, keeping the decision and the assignment visually together.
Example: Conditional Assignments
public class Main {
public static void main(String[] args) {
int score = 55;
String result;
if (score >= 60) {
result = "Pass"; // computed and assigned inside each branch
} else {
result = "Fail";
}
System.out.println(result);
}
}
Login to try C/C++/Java/PHP code in the editor
Checking Boolean Toggles
A single boolean variable as the condition, like if (isPremium) {...} else {...}, reads almost like plain English and is the cleanest way to branch behavior based on a feature flag or account status.
Example: Checking Boolean Toggles
public class Main {
public static void main(String[] args) {
boolean isPremium = true;
if (isPremium) {
System.out.println("Premium features unlocked");
} else {
System.out.println("Standard features only");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Complex Conditions in If-Else
Combining && and || inside the condition lets an if-else react to compound business rules, like requiring both a minimum age AND parental consent before allowing an action.
Example: Complex Conditions in If-Else
public class Main {
public static void main(String[] args) {
int age = 16;
boolean hasParentalConsent = true;
if (age >= 18 || (age >= 13 && hasParentalConsent)) {
System.out.println("Allowed");
} else {
System.out.println("Not allowed");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Nested If-Else Blocks
Nesting if-else blocks inside each other builds a genuine decision tree, where each level narrows down the possibilities further -- useful, though past 2-3 levels deep it's often clearer to refactor into an else-if ladder or switch instead.
Example: Nested If-Else Blocks
public class Main {
public static void main(String[] args) {
int score = 72;
if (score >= 90) {
System.out.println("A");
} else {
if (score >= 70) { // narrows down further within the else branch
System.out.println("B");
} else {
System.out.println("C");
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: