Short, complete programs showing if...else in situations you will actually meet.
Example A, Discount Eligibility
int total = 1200;
int minimumForDiscount = 500;
boolean isMember = true;
if (isMember && total >= minimumForDiscount) {
int discount = total / 10;
int finalPrice = total - discount;
System.out.println("You saved 10% and now pay " + finalPrice);
} else {
System.out.println("No discount. You pay " + total);
}
Note the && combining two conditions. That is a very common shape, and short-circuit evaluation means the discount logic only runs when both are true.
Example B, A Safe Null Check Before Use
String username = getUsername();
if (username == null || username.isBlank()) {
System.out.println("No username supplied, using Guest");
} else {
System.out.println("Welcome back, " + username);
}
The || here is what makes it safe. If username is null, the left side is true and Java never evaluates the right side, so isBlank() is never called on a null reference.
Example C, A Grading Decision
int marks = 87;
int topMark = 90;
if (marks >= topMark) {
System.out.println("Grade A");
} else {
System.out.println(marks >= 75 ? "Grade B" : "Needs work");
}
That inner ternary shows when nesting is reasonable. One small ternary inside a branch is easy to read; a ternary nested five levels deep is not.
Frequently Asked Questions
Can an else exist without an if?
No. An else must always be attached to a preceding if that has not already been paired with another else. Java will not compile a standalone else.
Can I have several else blocks on one if?
No. One if can have at most one else. When you need more branches you want an if...else if ladder, which is covered on our if...else if ladder page.
Why does if (count) not compile?
Because Java has no truthy or falsy values. A condition must be strictly a boolean expression, so write if (0 < count) instead. The explicit form also documents your intent for the next reader.
Is the condition evaluated more than once?
No, exactly once. This matters when the condition itself calls a method, because that method runs a single time regardless of what happens inside the branches.
Can I put any statement inside an if block?
Yes, including declarations, assignments, method calls, loops and further if statements. Just remember that a variable declared inside the block will not exist outside it.
Should I use a ternary or an if...else?
Use a ternary when you are only producing a value and the whole thing fits on one readable line. Use if...else when the branches contain several statements, or when the condition is complex enough that inlining it would hurt clarity.