Operators and expressions

Java · Essentials · 10 min

Most bugs in beginner code come from integer division, precedence or comparing the wrong way — this lesson heads them off.

The arithmetic operators + - * / % behave as expected with one big surprise: when both operands are integers, / performs integer division and throws away the fraction. 7 / 2 is 3, while 7 / 2.0 is 3.5. % gives the remainder (7 % 2 == 1), handy for "every n-th" logic.

Mixed expressions are widened automatically to the larger type (int + double → double). Going the other way needs an explicit cast, which can lose information: (int) 3.99 is 3 (it truncates, it does not round).

Shortcuts: x += 5 means x = x + 5 (and casts back to the type of x). i++ and ++i both add one; they differ only in the value the expression yields, so avoid using them inside larger expressions.

Comparison operators == != < <= > >= return a boolean. For primitives == compares values. For objects it compares references, which is why strings need .equals (next lesson).

The logical operators && and || short-circuit: the right side is evaluated only if needed. That makes guards like s != null && s.isEmpty() safe. ! negates.

The ternary operator chooses between two values: String label = n == 1 ? "item" : "items";.

Precedence follows math (* before +), and comparison binds tighter than &&, which binds tighter than ||. When in doubt, add parentheses — readers will thank you.

Example

public class Ops {
    public static void main(String[] args) {
        System.out.println(7 / 2);          // 3   (integer division)
        System.out.println(7 / 2.0);        // 3.5
        System.out.println(7 % 3);          // 1
        System.out.println((int) 3.99);     // 3   (cast truncates)
        System.out.println(Math.round(3.5)); // 4

        int score = 10;
        score += 5;                          // 15
        String s = null;
        boolean empty = s != null && s.isEmpty(); // short-circuit: no NPE
        String label = score >= 15 ? "pass" : "fail";
        System.out.println(score + " " + empty + " " + label); // 15 false pass
    }
}

Remember

  • int / int truncates — make one operand a double for a fractional result
  • Casting a double to int truncates toward zero; use Math.round to round
  • && and || short-circuit, so they can guard against null

Watch out for

  • Computing an average as sum / count with two ints and silently losing the fraction.

Check yourself

  1. What is the value of `double avg = 5 / 2;`?
  2. In `a != null && a.length() > 3`, when is `a.length()` evaluated?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html