Java Arithmetic Operators

Arithmetic operators are the ones you already know from everyday maths, plus a couple of Java-specific twists. They let you add, subtract, multiply, divide, and find remainders, and they behave differently depending on whether you feed them whole numbers or decimals.

The five arithmetic operators

Java has five core arithmetic operators. Four of them are obvious, but the fifth, the modulus operator, trips up many beginners, so it is worth learning well.

OperatorNameExampleResult
+Addition8 + 210
-Subtraction8 - 26
*Multiplication8 * 216
/Division8 / 24
%Modulus (remainder)8 % 32

Basic calculations

Here are the first four operators used on two whole numbers. Each line stores the outcome in its own variable so you can print and compare them.

Add, subtract, multiply, divide

public class Main {
  public static void main(String[] args) {
    int x = 12;
    int y = 5;

    System.out.println(x + y); // 17
    System.out.println(x - y); // 7
    System.out.println(x * y); // 60
    System.out.println(x / y); // 2  (integer division, remainder dropped)
  }
}
Note: When both operands are integers, division throws away the remainder rather than rounding. So 12 / 5 is 2, not 2.4. To keep the decimals, make at least one operand a double, for example 12.0 / 5.

The modulus operator

The percent sign does not mean percentage in Java. It gives you the remainder left over after division. This is surprisingly useful: a number is even when it divides by two with no remainder, and you can use modulus to wrap values around a fixed range, such as hours on a clock.

Using modulus to test for even numbers

public class Main {
  public static void main(String[] args) {
    int number = 14;

    System.out.println(14 % 5); // 4  (14 = 5*2 + 4)
    System.out.println(number % 2); // 0  so 14 is even
    System.out.println(7 % 2);      // 1  so 7 is odd
  }
}

Increment and decrement

Because adding or subtracting one is so common, Java gives you the shorthand operators ++ and --. They increase or decrease a variable by exactly one, and you will see them constantly inside loops.

Increment and decrement

public class Main {
  public static void main(String[] args) {
    int count = 5;

    count++; // same as count = count + 1
    System.out.println(count); // 6

    count--; // same as count = count - 1
    System.out.println(count); // 5
  }
}
Note: The + operator does double duty: with numbers it adds, but with text it joins strings together. So 2 + 3 is 5, while "2" + "3" is the string "23".