Lesson 4 of 23
In progress
if, else and boolean logic
Write conditions that read like the rule they encode, avoid the assignment-in-condition mistake, and flatten nested branches.
A condition decides which path a program takes. Java’s syntax is small; the difficulty is writing conditions that another person can check against the requirement.
What you will learn
- Write
if,else ifandelsebranches. - Combine boolean expressions without losing the intent.
- Flatten nesting with early returns.
The shape
public class Grade {
public static void main(String[] args) {
int score = 78;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else if (score >= 70) {
System.out.println("C");
} else {
System.out.println("Below C");
}
}
}
Branches are checked in order, and the first true one wins. That ordering is the logic: writing if (score >= 70) first would label a 95 as a C.
The condition must be a boolean expression. Java will not accept an integer, so if (count) is a compile error — unlike C. That strictness removes a whole family of bugs.
Comparison and equality
String input = "yes";
if (input.equals("yes")) {
System.out.println("confirmed");
}
Use equals for strings and objects. == compares references, and it happens to work for literal strings because they are interned, which means the bug appears only once the value arrives from input or a method.
For null-safe comparison, put the known non-null value first: "yes".equals(input) returns false for a null input instead of throwing. That idiom is worth remembering for form handling.
Numeric comparison uses ==, <, >, <=, >=. For doubles, exact equality is unreliable after arithmetic, so compare with a tolerance:
double a = 0.1 + 0.2;
if (Math.abs(a - 0.3) < 1e-9) {
System.out.println("close enough");
}
Combining conditions
boolean member = true;
boolean hasCoupon = false;
int totalPaise = 120000;
boolean discount = (member || hasCoupon) && totalPaise >= 100000;
&& binds tighter than ||, so the parentheses above are required for the intended meaning: member or coupon, and a minimum total. Without them, the expression means member, or coupon and the minimum, which is a different rule.
Short-circuit evaluation makes null checks safe:
if (name != null && !name.isBlank()) {
System.out.println("Hello, " + name.strip());
}
The second operand is not evaluated when the first is false, so name is never dereferenced while null. Reverse the order and the check is useless.
Nesting and early return
Deeply nested branches are hard to check against a requirement. A method that returns early reads better:
public class Access {
static String check(String user, boolean admin, boolean active) {
if (user == null) {
return "no user";
}
if (!active) {
return "inactive account";
}
if (admin) {
return "full access";
}
return "limited access";
}
}
Each guard states one rule and leaves. The alternative — nested if blocks with a shared final return — requires the reader to hold several conditions in mind at once.
Early returns are also the natural way to validate input at the top of a method, before any work happens. Keeping validation separate from the main path makes both easier to read.
Common patterns
// Range check
if (age >= 18 && age <= 65) { /* working age */ }
// Membership
if (role.equals("admin") || role.equals("owner")) { /* privileged */ }
// Negation of a compound
if (!(a && b)) { /* at least one is false */ }
De Morgan’s law is worth knowing when a negation gets awkward: !(a && b) is !a || !b, and sometimes the expanded form is clearer.
if versus a lookup
When a chain of else if compares one variable against many constants, a switch or a map is clearer. When each branch calls a different method with different arguments, a chain is fine.
String label;
if (status == null) {
label = "unknown";
} else if (status.equals("paid")) {
label = "Paid";
} else {
label = "Pending";
}
That is readable at three branches and unreadable at eight. The signal to change the structure is when the reader needs to scroll to see the start and the end.
Formatting
Braces on every branch, even a single statement. The alternative compiles and invites a bug when a second statement is added later without braces.
Indent consistently, keep the condition on one line if possible, and put the body on its own lines. Java has no significant whitespace, which means the compiler will not save you from misalignment; the convention exists because humans read the indentation.
Writing if (x = 5) in a language that allows it, and expecting a comparison. Java rejects the assignment because it is not a boolean, which is one of the few places where its strictness pays off immediately.
Write a method that returns a shipping charge in paise: free for members, 4900 for orders of 50000 or more, 9900 otherwise, and 0 for orders with no items. Then test it with four cases.
Show solution
public class Shipping { static long charge(long orderPaise, int items, boolean member) { if (items == 0) { return 0L; } if (member) { return 0L; } if (orderPaise >= 50_000L) { return 4_900L; } return 9_900L; } public static void main(String[] args) { System.out.println(charge(0, 0, false)); // 0 System.out.println(charge(20_000, 2, true)); // 0 System.out.println(charge(60_000, 3, false)); // 4900 System.out.println(charge(10_000, 1, false)); // 9900 } } The guards run in order of importance: no items beats membership, which beats the order value. Returning early keeps each rule visible and makes the four test cases easy to trace.
Recap
- Branches are checked in order, so the order is part of the rule.
&&short-circuits, which makes null checks safe when the null test comes first.- Prefer early returns and flat conditions over deep nesting.
Next, switch for choosing among several fixed values, including the modern arrow form.
Can if conditions span lines?
Should I use else after a return?
Progress is saved in this browser only. No account, no email.