Java Operators

Java operators are symbols that perform operations on values and variables, such as adding numbers, comparing them or combining conditions.

Arithmetic Operators

+ adds, - subtracts, * multiplies, / divides and % gives the remainder (modulus). The modulus operator is great for checking whether a number is even.

public class Main {
    public static void main(String[] args) {
        int a = 17, b = 5;
        System.out.println(a + b);
        System.out.println(a - b);
        System.out.println(a * b);
        System.out.println(a / b);
        System.out.println(a % b);
        System.out.println(10 % 2 == 0 ? "even" : "odd");
    }
}
22
12
85
3
2
even

Increment, Decrement and Assignment

++ adds one and -- subtracts one. In the prefix form (++x) the change happens before the value is used; in the postfix form (x++) after. Compound assignment operators like += combine an operation with assignment.

public class Main {
    public static void main(String[] args) {
        int x = 5;
        System.out.println(x++); // prints 5, then x becomes 6
        System.out.println(++x); // x becomes 7, then prints 7
        int total = 10;
        total += 5;
        total *= 2;
        total -= 4;
        System.out.println(total);
    }
}
5
7
26

Comparison and Logical Operators

Comparison operators (==, !=, >, <, >=, <=) return a boolean. Logical operators combine booleans: && (and), || (or), ! (not). && and || short-circuit: the right side is skipped if the left side already decides the answer.

public class Main {
    public static void main(String[] args) {
        int age = 22;
        boolean hasTicket = true;
        System.out.println(age >= 18 && hasTicket);
        System.out.println(age < 13 || age > 65);
        System.out.println(!hasTicket);
    }
}
true
false
false

The Ternary Operator

condition ? valueIfTrue : valueIfFalse is a compact if-else that produces a value.

public class Main {
    public static void main(String[] args) {
        int stock = 0;
        String label = stock > 0 ? "In stock" : "Sold out";
        System.out.println(label);
    }
}
Sold out

Operator Precedence

  • *, / and % are evaluated before + and -.
  • Comparison happens before && and ||, and && before ||.
  • Assignment operators are evaluated last.
  • Use parentheses whenever the order is not obvious: (a + b) * c.

Frequently asked questions

What is the difference between i++ and ++i in Java?

Both add one to i. i++ returns the old value and then increments, while ++i increments first and returns the new value. On their own line they behave the same.

What does % mean in Java?

It is the remainder (modulus) operator. 17 % 5 is 2 because 17 divided by 5 leaves a remainder of 2.

What is the difference between & and && in Java?

&& short-circuits, so the right side is not evaluated if the left is false. & always evaluates both sides and is also used as a bitwise AND on integers.