Java Notes
Complete guide to Java if-else statements — simple if, if-else, if-else-if ladder, nested if, and best practices with practical examples and common patterns.
The if-else statement is Java's fundamental decision-making construct. It executes different blocks of code based on whether a condition evaluates to true or false.
Simple If Statement
public class SimpleIf {
public static void main(String[] args) {
int age = 20;
// Simple if — executes block only if condition is true
if (age >= 18) {
System.out.println("You are an adult.");
System.out.println("You can vote.");
}
// If condition is false, block is skipped
int temperature = 15;
if (temperature > 30) {
System.out.println("It's hot!"); // This won't execute
}
System.out.println("Program continues regardless.");
}
}You are an adult. You can vote. Program continues regardless.
If-Else Statement
public class IfElse {
public static void main(String[] args) {
int number = -5;
if (number >= 0) {
System.out.println(number + " is positive or zero");
} else {
System.out.println(number + " is negative");
}
// Practical: Login validation
String username = "admin";
String password = "secret123";
if (username.equals("admin") && password.equals("secret123")) {
System.out.println("Login successful! Welcome, admin.");
} else {
System.out.println("Invalid credentials. Access denied.");
}
// Even/Odd check
int num = 42;
if (num % 2 == 0) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
}
}
}-5 is negative Login successful! Welcome, admin. 42 is even
If-Else-If Ladder
For multiple conditions checked sequentially:
public class IfElseIfLadder {
public static void main(String[] args) {
int score = 76;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
System.out.println("Score: " + score + " → Grade: " + grade);
// BMI Calculator
double weight = 70; // kg
double height = 1.75; // meters
double bmi = weight / (height * height);
String category;
if (bmi < 18.5) {
category = "Underweight";
} else if (bmi < 25.0) {
category = "Normal weight";
} else if (bmi < 30.0) {
category = "Overweight";
} else {
category = "Obese";
}
System.out.printf("BMI: %.1f → %s%n", bmi, category);
}
}Score: 76 → Grade: C BMI: 22.9 → Normal weight
Nested If Statements
public class NestedIf {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
boolean hasInsurance = true;
if (age >= 18) {
System.out.println("Age requirement: PASSED");
if (hasLicense) {
System.out.println("License check: PASSED");
if (hasInsurance) {
System.out.println("Insurance check: PASSED");
System.out.println("✓ You can drive!");
} else {
System.out.println("✗ Need insurance first.");
}
} else {
System.out.println("✗ Need a driver's license first.");
}
} else {
System.out.println("✗ Must be 18 or older to drive.");
}
}
}Age requirement: PASSED License check: PASSED Insurance check: PASSED ✓ You can drive!
Practical Examples
Leap Year Checker
2024 is a leap year Verify: true
Triangle Type Classifier
Valid triangle with sides: 5, 5, 8 Type: Isosceles
Single-Line If (Without Braces)
public class SingleLineIf {
public static void main(String[] args) {
int x = 10;
// Without braces — only ONE statement
if (x > 5) System.out.println("x is greater than 5");
// DANGEROUS! Only first line is part of if:
if (x > 100)
System.out.println("This is conditional");
System.out.println("This ALWAYS executes (not part of if!)");
// BEST PRACTICE: Always use braces
if (x > 5) {
System.out.println("Clear and safe");
}
}
}x is greater than 5 This ALWAYS executes (not part of if!) Clear and safe
Common Mistakes
- Using
=instead of==—if (x = 5)is assignment (compile error for int). Use==for comparison. - Forgetting braces —
if (cond) stmt1; stmt2;— only stmt1 is conditional! Always use{}. - Comparing Strings with
==— Use.equals()for String comparison, not==. - Redundant boolean comparison —
if (isValid == true)should beif (isValid). - Unreachable else — if your if-else-if covers all cases (like checking > and <=), the final else is unreachable.
- Too many nested ifs — refactor to early returns or switch/pattern matching for readability.
Interview Questions
Q1: What is the difference between if-else and ternary operator?
Answer: Both make decisions, but the ternary operator (condition ? value1 : value2) is an expression that returns a value, while if-else is a statement that executes blocks. Ternary is for simple value selection; if-else for complex logic with multiple statements.
Q2: Can you have an if without else?
Answer: Yes. The else clause is optional. A standalone if simply skips the block when the condition is false and continues with the next statement.
Q3: What happens if you omit braces in an if statement?
Answer: Only the first statement after the if is conditional. Subsequent statements always execute regardless of the condition. This is a common source of bugs, which is why best practice is to always use braces.
Q4: How do you avoid deep nesting of if statements?
Answer: Use (1) early returns (guard clauses) to handle edge cases first, (2) extract complex conditions into named boolean variables, (3) use switch statements or polymorphism for multiple type checks, (4) combine conditions with logical operators.
Q5: What is a dangling else problem?
Answer: When nested ifs lack braces, it's ambiguous which if an else belongs to. In Java, else always pairs with the nearest unmatched if. Using braces eliminates ambiguity: if (a) { if (b) { ... } } else { ... }.
Summary
The if-else statement is Java's primary decision-making construct. Use simple if for single conditions, if-else for binary choices, and if-else-if ladders for multiple conditions. Always use braces, compare Strings with .equals(), and refactor deep nesting into guard clauses or extracted methods for readability.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for If-Else Statements in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, control, statements
Related Java Master Course Topics