Coding Techniques
Operators and Expressions · Study material
Overflow-safe arithmetic
Widen before computing, use the Math.*Exact methods to detect overflow, and compute mid-points as lo + (hi - lo) / 2 (or with >>> 1) – the bug that once broke binary search in the JDK itself.
public class Main {
public static void main(String[] args) {
int big = 1_500_000_000;
System.out.println(big + big); // wraps around
System.out.println((long) big + big); // widen first
try {
System.out.println(Math.addExact(big, big));
} catch (ArithmeticException e) {
System.out.println("overflow detected: " + e.getMessage());
}
// Average without overflow
int lo = 2_000_000_000, hi = 2_100_000_000;
System.out.println((lo + hi) / 2 + " " + (lo + (hi - lo) / 2) + " " + ((lo + hi) >>> 1));
}
}
-1294967296 3000000000 overflow detected: integer overflow -97483648 2050000000 2050000000
Writing readable conditions
// ✘ Hard to read: precedence and negations mixed together
if (!(age < 18 || !hasId) && score > 60 & attempts < 3) { … }
// ✔ Name the parts and use && / || only
boolean adult = age >= 18;
boolean eligible = adult && hasId && score > 60 && attempts < 3;
if (eligible) { … }
// ✔ Null-safe comparisons
if ("admin".equals(role)) { … } // literal first: no NullPointerException if role is null
if (Objects.equals(a, b)) { … } // works when either side is null Handy bit manipulation idioms
| Task | Expression |
|---|---|
| Is n even? | (n & 1) == 0 |
| Is n a power of two? | n > 0 && (n & (n - 1)) == 0 |
| Set bit k | x |= 1 << k |
| Clear bit k | x &= ~(1 << k) |
| Toggle bit k | x ^= 1 << k |
| Test bit k | (x >> k & 1) == 1 |
| Count set bits | Integer.bitCount(x) |
| Multiply / divide by 2ⁿ | x << n / x >> n |
Operator checklist
- Use parentheses in any expression mixing operator families.
- Keep ++ and -- as standalone statements.
- Use && and || for conditions; &, |, ^ for bits.
- Compare objects with equals() / Objects.equals().
- Watch for overflow in sums, products and mid-points.
- Prefer if/else to nested ternaries beyond two levels.