Operators and expressions

Core Java · lesson 2 of 42 · 3 min read

Use arithmetic, comparison and logical operators without falling into the classic traps.

Open this lesson in the learning hub

Key points

  • Integer division throws the remainder away: 7 / 2 is 3. Make one side a double to get 3.5.
  • % is the remainder. n % 2 == 0 is the standard even check.
  • i++ returns the old value then increments; ++i increments first. Keep them out of bigger expressions.
  • && and || short-circuit: the right side is skipped once the answer is known. That is what makes null guards safe.
  • == compares values for primitives but identity for objects. Use equals() on objects.
  • The ternary cond ? a : b is an expression, so you can assign or return it directly.

Example

public class Main {
    public static void main(String[] args) {
        int a = 7, b = 2;
        System.out.println("7 / 2   = " + (a / b) + "   (integer division truncates)");
        System.out.println("7 % 2   = " + (a % b));
        System.out.println("7 / 2.0 = " + (a / 2.0));

        int i = 5;
        System.out.println("i++ returns " + (i++) + ", i is now " + i);
        System.out.println("++i returns " + (++i));

        int total = 10;
        total += 5;
        total *= 2;
        System.out.println("compound assignment -> " + total);

        boolean safe = (b != 0) && (10 / b > 4);
        System.out.println("&& short-circuits, so no divide by zero: " + safe);

        String winner = a > b ? "a" : "b";
        System.out.println("ternary picks: " + winner);

        System.out.println("1 << 10 = " + (1 << 10) + ", 13 & 1 = " + (13 & 1));
    }
}

Integer division truncates, and && stops as soon as it knows the answer.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.