← Back to Core Java Course | Chapter 4: Control Flow | Lesson 2 of 9

Java if-else Statement

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

java
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
		}
	}
}

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

java
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);
	}
}

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

java
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");
		}
	}
}

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

java
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");
		}
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.