The if, else and the logical operators are the machinery that branches your program. An if runs a block when a condition is true, an else clause covers the case when it is not, and the operators &&, || and ! combine the conditions into a single yes-or-no answer. Get those three right and you can express every decision that your program will ever need to make.
This is the first lesson in the Java if-else and Loops module, and the next lesson in this module is about "How Does switch Work, Including the Modern Arrow Form?".
What does an if/else statement actually do?
An if statement evaluates a boolean expression and it runs the block that follows when the result is true. Add an else and the compiler guarantees that one of the two branches runs, so there is no third path where nothing happens at all. That guarantee is why an if and else pair is safer than a bare if whenever a value has to end up being set. The compiler forces you to handle the alternative instead of leaving it to chance.
Here is a parking fee calculator. The first thirty minutes are free, the next hour costs a flat rate, and everything beyond that is charged per extra minute.
public class ParkingFee {
public static void main(String[] args) {
int minutes = 95;
double fee = calculateFee(minutes);
System.out.println("Parked for " + minutes + " minutes");
System.out.println("Fee: " + fee);
}
static double calculateFee(int minutes) {
if (minutes <= 30) {
return 0.0;
} else if (minutes <= 90) {
return 3.50;
} else {
return 3.50 + (minutes - 90) * 0.25;
}
}
}Run it and the console prints two lines.
Parked for 95 minutes
Fee: 4.75Three details are worth noticing. The condition is a plain boolean expression, so it reads like a sentence. Each branch returns immediately, which means the method can never fall off the end without producing a value, and the compiler is satisfied that every path returns something. And the second condition is only reached when the first one fails, so you can order the tests from the most specific to the least without worrying about the ranges overlapping.
How do you build a chain of conditions with else if?
A chain of else if clauses is a ladder. The first matching condition wins and the remaining clauses are skipped entirely, so the order of the tests changes the meaning of the code. You write it from the top to the bottom with the strictest test first and it behaves like a lookup table. You write it the other way round and the first clause swallows all of the later cases.
public class DiscountLadder {
public static void main(String[] args) {
int items = 7;
double subtotal = 120.0;
double rate = discountRate(items, subtotal);
System.out.println("Items: " + items + ", subtotal: " + subtotal);
System.out.println("Discount rate: " + (rate * 100) + "%");
System.out.println("Final: " + (subtotal * (1 - rate)));
}
static double discountRate(int items, double subtotal) {
if (items >= 10 || subtotal >= 200) {
return 0.15;
} else if (items >= 5) {
return 0.10;
} else if (subtotal >= 50) {
return 0.05;
} else {
return 0.0;
}
}
}Seven items with a subtotal of 120.00 earns the 10% tier, because the first condition failed on both counts and the second one matched. That first clause uses the || operator, so either condition on its own is enough for the top tier.
And if you swap it for the && operator, then a shopper with ten items but a small basket quietly falls through to a lower tier, and that is exactly the kind of bug that a discount ladder is supposed to prevent.
Why do the logical operators short-circuit?
The two double-character operators are short-circuiting, which means Java evaluates the left operand first and it stops as soon as the answer is certain. With &&, if the left side is false then the whole expression is false, so the right side is never evaluated at all. With ||, if the left side is true then the whole expression is true, so again the right side is skipped.
public class ShortCircuit {
static int calls = 0;
static boolean check() {
calls++;
return false;
}
public static void main(String[] args) {
boolean a = check() && check();
System.out.println("a=" + a + " calls=" + calls);
calls = 0;
boolean b = check() & check();
System.out.println("b=" + b + " calls=" + calls);
}
}The short-circuiting version made one call, and the non-short-circuiting version made two.
a=false calls=1
b=false calls=2And the single-character forms are the bitwise operators. They always evaluate both sides, which is what you want for the boolean flags and exactly what you do not want for a guard clause.
the expression does it evaluate the right side? the typical use
------------------- ------------------------------- -----------------
a && b only when a is true the guarded checks
a || b only when a is false the fallbacks
a & b always the boolean flags
a | b always the boolean flags
!a not applicable the negation
What is the dangling else problem?
Java attaches every else to the nearest unmatched if. You leave the braces off and the structure of your program can change without a single character of the condition changing. That is the dangling else, and it is a classic source of the bugs that survive a review because the code looks right at a glance.
public class DanglingElse {
public static void main(String[] args) {
int score = 45;
if (score >= 50)
if (score >= 90)
System.out.println("excellent");
else
System.out.println("pass");
else
System.out.println("fail");
}
}The output is "fail", and it is not what most people expect on the first read. The inner else belongs to the inner if, which leaves the outer if without an else of its own, so the final else attaches to the outer if after all.
The rule that prevents all of this is simple. You always use the braces, even for a single statement. If your editor adds them for you then you leave them in, and if you write them yourself then you get the structure that you intended rather than the one that the parser inferred.
How do you combine several conditions safely?
The short-circuiting is what makes the defensive checks safe. A null check that is placed before the dereference means that the dereference never happens when the value is missing, because the second operand is never evaluated.
public class Eligibility {
public static void main(String[] args) {
int age = 17;
boolean hasLicense = false;
boolean canRent = age >= 18 && hasLicense;
System.out.println("age " + age + ", license " + hasLicense);
System.out.println("can rent: " + canRent);
String coupon = null;
boolean hasDiscount = coupon != null && coupon.equals("SAVE10");
System.out.println("has discount: " + hasDiscount);
}
}Both of the guards behaved as intended.
age 17, license false
can rent: false
has discount: falseAnd if you swap the two operands in the second check then the program crashes with a null pointer exception instead of printing a line, because the coupon.equals(...) would then be evaluated on a null reference. The order of the operands is not a stylistic detail. It is the whole safety mechanism. The same rule covers the collections, so you test items != null && !items.isEmpty() before you call items.size().
What to remember
- An if and else pair always runs exactly one branch, and an else if chain runs the first matching clause and skips the rest.
- You order an else if ladder from the strictest to the loosest, because the first match wins and nothing after it is tested.
- The && and || operators short-circuit, and the single-character bitwise forms always evaluate both sides.
- You put the cheap or the most likely to fail test first, and you put any null or range check before the test that would crash.
- You always brace your blocks, because the dangling else is a parsing problem and the braces remove it entirely.
- If you are nesting the if statements that all test the same variable then a switch statement will usually read better.
Try it yourself: write a program that decides whether an order gets the free delivery. The free delivery applies when the order total is over 40, or when the customer is a member and the order is over 15, and it never applies to the orders of 5 or less. Print the delivery charge, which is 0, 250 or 495 pence, for at least five orders and include the boundary cases of 5, 15 and 40. Then deliberately swap the operands in one of your checks, run it, and use the output to explain why the order of the operands matters.