Skip to content
Laviyx Learn

Try

Java course menu

Java Operators: Arithmetic, Comparison, Logical, Assignment and Ternary

Learn Java operators: + - * / %, integer division, compound assignment, ++ and --, comparison and logical operators, short-circuit evaluation, the ternary operator, string concatenation with +, and operator precedence.

Beginner10 min readUpdated
On this page

Operators are the symbols that calculate, compare and combine values. Most work like their maths equivalents; a few have behaviour every Java programmer must know.

Arithmetic operators#

OperatorMeaningExampleResult
+Addition7 + 29
-Subtraction7 - 25
*Multiplication7 * 214
/Division7 / 23
%Remainder7 % 21
Java
public class Main {
    public static void main(String[] args) {
        System.out.println(7 / 2 + " " + 7.0 / 2);
        System.out.println(7 % 2 + " " + 20 % 6 + " " + 7.5 % 2);
        System.out.println(-7 / 2 + " " + -7 % 2);
    }
}
Output
3 3.5
1 2 1.5
-3 -1
  • Integer division drops the fraction (towards zero).
  • In Java, % also works on decimals: 7.5 % 2 is 1.5.
  • Integer division by zero throws an ArithmeticException; dividing a double by zero gives Infinity (or NaN for 0.0 / 0).

Useful % patterns#

Java
public class Main {
    public static void main(String[] args) {
        int n = 2026;
        System.out.println(n % 2 == 0);     // even?
        System.out.println(n % 10);         // last digit
        System.out.println(n / 10);         // remove the last digit

        int totalMinutes = 135;
        System.out.println(totalMinutes / 60 + "h " + totalMinutes % 60 + "m");
    }
}
Output
true
6
202
2h 15m

Java has no power operator; ^ is bitwise XOR. Use Math.pow(2, 10), which returns a double (1024.0).

Compound assignment#

Java
public class Main {
    public static void main(String[] args) {
        int balance = 1000;
        balance += 250;   // 1250
        balance -= 100;   // 1150
        balance *= 2;     // 2300
        balance /= 3;     // 766 (integer division)
        balance %= 7;     // 3
        System.out.println(balance);
    }
}
Output
3

Compound operators include an automatic cast: int x = 10; x *= 2.5; compiles and gives 25, while x = x * 2.5; does not compile.

Increment and decrement#

++ adds 1 and -- subtracts 1. Prefix (++i) changes the variable and then gives the new value; postfix (i++) gives the old value and then changes it:

Java
public class Main {
    public static void main(String[] args) {
        int a = 5;
        int b = ++a;   // a = 6, b = 6
        int c = 5;
        int d = c++;   // d = 5, c = 6
        System.out.println(a + " " + b + " " + c + " " + d);
    }
}
Output
6 6 6 5

On a line of its own, i++; and ++i; do the same thing.

Comparison operators#

==, !=, <, >, <= and >= produce a boolean:

Java
public class Main {
    public static void main(String[] args) {
        int age = 20;
        System.out.println(age == 20);
        System.out.println(age != 20);
        System.out.println(age >= 18);
    }
}
Output
true
false
true

For objects such as String, == compares references, not contents. Use a.equals(b); see Strings.

Logical operators#

OperatorMeaningTrue when
&&ANDboth sides are true
||ORat least one side is true
!NOTthe value is false

&& and || short-circuit: they stop as soon as the answer is known, which lets you guard a risky check:

Java
public class Main {
    public static void main(String[] args) {
        int count = 0;
        int total = 50;

        if (count != 0 && total / count > 10) {
            System.out.println("High average");
        } else {
            System.out.println("No data or low average");
        }
    }
}
Output
No data or low average

Because count != 0 is false, total / count is never evaluated, so there is no ArithmeticException.

The ternary operator#

condition ? a : b chooses one of two values:

Java
public class Main {
    public static void main(String[] args) {
        int marks = 72;
        String result = marks >= 40 ? "pass" : "fail";
        System.out.println(result);
    }
}
Output
pass

+ with strings#

If either operand of + is a String, + joins (concatenates) instead of adding. Evaluation goes left to right, which can surprise you:

Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Sum: " + 2 + 3);
        System.out.println("Sum: " + (2 + 3));
        System.out.println(2 + 3 + " is the sum");
    }
}
Output
Sum: 23
Sum: 5
5 is the sum

Operator precedence#

From highest to lowest (simplified):

  1. Postfix i++, i--
  2. Unary ++i, --i, !, -, casts
  3. * / %
  4. + -
  5. < > <= >= instanceof
  6. == !=
  7. &&
  8. ||
  9. ? :
  10. =, +=, -=, …

When in doubt, use parentheses: they cost nothing and make intent clear.

Common mistakes#

Practice#

Practice exercise

Given int seconds = 4000;, print it as hours, minutes and seconds in the form 1h 6m 40s.

Show solution
Java
public class Duration {
    public static void main(String[] args) {
        int seconds = 4000;
        int hours = seconds / 3600;
        int minutes = seconds % 3600 / 60;
        int secs = seconds % 60;
        System.out.println(hours + "h " + minutes + "m " + secs + "s");
    }
}
Output
1h 6m 40s

Practice exercise

Without running it, predict the output, then check:

Java
int x = 10;
System.out.println(x++ + ++x);
System.out.println(x);
Show solution
Java
public class Predict {
    public static void main(String[] args) {
        int x = 10;
        System.out.println(x++ + ++x);
        System.out.println(x);
    }
}
Output
22
12

Java evaluates left to right: x++ gives 10 (then x becomes 11), ++x makes x 12 and gives 12, and 10 + 12 = 22. Unlike C++, this is well defined in Java, but it is still hard to read, so avoid writing it in real code.

Key takeaway#

Finished this lesson?