Java — If Else
The if statement
An if statement runs code only when a condition is true:
int age = 25;
if (age >= 18) {
System.out.println("You are an adult.");
}
The condition must evaluate to a boolean — true or false. Unlike some languages, Java won't treat numbers as true/false. You must write an explicit comparison.
The if-else statement
Add an alternative path for when the condition is false:
int temperature = 5;
if (temperature > 30) {
System.out.println("It's hot outside.");
} else {
System.out.println("It's not that hot.");
}
One of the two blocks always executes — there's no in-between.
else-if chains
When you have multiple possible outcomes:
int score = 78;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
Java evaluates conditions top to bottom and runs the first matching block. Once a block runs, the rest are skipped. Order matters — put the most specific conditions first.
Nested conditions
You can place if statements inside other if statements:
boolean hasTicket = true;
int age = 16;
if (hasTicket) {
if (age >= 18) {
System.out.println("Welcome to the show.");
} else {
System.out.println("You need a guardian.");
}
} else {
System.out.println("Please buy a ticket first.");
}
Nesting works, but going more than two levels deep makes code hard to read. Refactor deep nests into separate methods or combine conditions with &&.
Combining conditions
Instead of nesting, use logical operators:
boolean hasTicket = true;
int age = 16;
if (hasTicket && age >= 18) {
System.out.println("Welcome to the show.");
} else if (hasTicket && age < 18) {
System.out.println("You need a guardian.");
} else {
System.out.println("Please buy a ticket first.");
}
This reads flatter and clearer than nested blocks. The ternary operator can compress simple decisions even further.
The ternary operator
int age = 20;
String status = (age >= 18) ? "adult" : "minor";
System.out.println(status); // adult
Format: condition ? valueIfTrue : valueIfFalse.
It's shorthand for a simple if-else that assigns a value. Use it for short, readable assignments. For complex logic, stick with if-else blocks.
Common mistakes
Forgetting braces
// Works — but dangerous
if (age >= 18)
System.out.println("adult");
System.out.println("You can vote."); // always runs!
Without braces, only the very next statement is conditional. The second println always executes regardless of the condition. Always use braces even for single-line bodies:
if (age >= 18) {
System.out.println("adult");
}
Comparing strings with ==
String color = "red";
// Wrong — compares object references
if (color == "red") { }
// Correct — compares content
if (color.equals("red")) { }
== checks if both variables point to the same object. .equals() checks if they contain the same text. Always use .equals() for string comparison.
Yoda conditions
// This compiles but is unusual
if (18 <= age) { }
// Preferred — reads naturally
if (age >= 18) { }
Put the variable on the left side. It reads like English and reduces mistakes.
Logical operators in conditions
boolean isStudent = true;
int age = 22;
double gpa = 3.5;
// AND — both conditions must be true
if (isStudent && age >= 21) {
System.out.println("Eligible for senior student discount.");
}
// OR — at least one must be true
if (age < 13 || age > 65) {
System.out.println("Discounted ticket price.");
}
// NOT — flips the boolean
if (!isStudent) {
System.out.println("Full price applies.");
}
Short-circuit evaluation
Java stops evaluating as soon as the result is known:
String name = null;
// Safe — first condition is false, second is never checked
if (name != null && name.length() > 0) {
System.out.println("Name has content.");
}
If name is null, name != null is false. Java skips name.length() > 0 entirely — preventing a NullPointerException. Always put the null check first.
Switch as alternative
When comparing one variable against many fixed values, switch reads cleaner than if-else chains:
String day = "Monday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
System.out.println("Weekday");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
}
Without break, execution "falls through" to the next case. This can be intentional (grouping Monday–Friday) or a bug. Modern Java's enhanced switch eliminates this:
String type = switch (day) {
case "Saturday", "Sunday" -> "Weekend";
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday";
default -> "Invalid";
};
Mini Practice
- Write a program that classifies a number as positive, negative, or zero
- Create a grade calculator with if-else-if for A, B, C, D, F
- Check if a year is a leap year (divisible by 4, except centuries unless divisible by 400)
- Write a program that finds the largest of three numbers using if-else
- Convert the grade calculator to use the ternary operator for each grade
Next: loops — repeating actions →
Related Topics
Frequently Asked Questions about If Else
What is If Else in Java?
If Else is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn If Else?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn If Else.
Why is If Else important in Java?
If Else is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.