Arithmetic Operators

The Operators

OperatorNameExampleResult
+addition10 + 313
-subtraction10 - 37
*multiplication10 * 330
/division10 / 33 (int division)
%modulus (remainder)10 % 31

Example

Example

public class Main {
    public static void main(String[] args) {
        int a = 17, b = 5;
        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a * b = " + (a * b));
        System.out.println("a / b = " + (a / b));
        System.out.println("a % b = " + (a % b));
        System.out.println("17.0 / 5 = " + (17.0 / 5));
        System.out.println("-17 % 5 = " + (-17 % 5));
    }
}

Output

a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
17.0 / 5 = 3.4
-17 % 5 = -2

Uses of Modulus

Example

The remainder operator is surprisingly useful: even/odd checks, getting the last digit, wrapping around.

public class Main {
    public static void main(String[] args) {
        int n = 2345;
        System.out.println(n + " is even? " + (n % 2 == 0));
        System.out.println("Last digit: " + n % 10);
        int totalMinutes = 135;
        System.out.println(totalMinutes / 60 + " h " + totalMinutes % 60 + " min");
    }
}

Output

2345 is even? false
Last digit: 5
2 h 15 min