Boolean Logic
There is no “truthy”
A condition must be a boolean. Nothing else.
Comparison
| Operator | Meaning |
|---|---|
== != |
equal / not equal (identity for objects) |
< > <= >= |
ordering |
The wrapper trap — small values are cached:
Logical operators
&& and || short-circuit — the right side is skipped when the result is already known.
That protects you:
| a | b | a && b |
a || b |
!a |
|---|---|---|---|---|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
Ternary
Fine for simple cases, never nest it — use switch instead.
Dealing with null
Java tells you exactly what was null:
Strategies:
Tip
Never return null for a collection — return an empty one. It saves your callers hundreds
of null checks.
Keep conditions readable
De Morgan: !(a && b) ≡ !a || !b, and !(a || b) ≡ !a && !b.
★ Exercises
boolean isLeapYear(int year)— divisible by 4, not by 100, unless by 400.- Why is
"a" == "a"often true, yet unreliable? Try it in JShell. - Rewrite
!(age < 18 || blocked)without the leading!. boolean isValidPassword(String)— 8+ chars, a digit, an uppercase letter;nullis invalid but must not throw.- What does
1 == 1.0print, and why?