Java Tutorial · Java Basics · Lesson 9 of 37

Java Operators

Arithmetic, assignment, comparison, logical and ternary operators.

Arithmetic

+ - * / % plus increment ++ and decrement --. Dividing two integers gives an integer result:

Example 1
public class Main {
    public static void main(String[] args) {
        int a = 17, b = 5;
        System.out.println(a / b);    // integer division
        System.out.println(a % b);    // remainder
        System.out.println(a / 5.0);  // one double makes it decimal
        int count = 10;
        count += 5;
        count *= 2;
        System.out.println(count++ + " then " + count);
    }
}

Output

3
2
3.4
30 then 31

Run this on your computer — see “Get Started” for setup.

Comparison and logical

== != > < >= <= compare values; && (and), || (or) and ! (not) combine booleans. && and || short-circuit: the right side isn't evaluated if the result is already known.

Ternary

condition ? a : b picks a value:

Example 2
public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean hasTicket = true;
        System.out.println(age >= 18 && hasTicket);
        String label = age >= 18 ? "adult" : "minor";
        System.out.println(label);
        String name = null;
        System.out.println(name != null && name.length() > 3);  // short-circuit avoids a crash
    }
}

Output

true
adult
false

Run this on your computer — see “Get Started” for setup.

For objects (including String), == checks whether two references point to the same object. Use .equals() to compare contents — see Java strings output puzzle.

Test yourself

What does 7 / 2 evaluate to in Java?

  1. 3
  2. 3.5
  3. 4
  4. 3.0
Show answer

Answer: 3

Practice next