Arithmetic Operators

Maths symbols

SymbolMeaningExampleAnswer
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23 (!)
%remainder7 % 21

Integer division

When both numbers are int, Java gives back an int and throws away the decimal part. If either one is a double, you get the decimal answer:

public class Main {
    public static void main(String[] args) {
        System.out.println(7 / 2);
        System.out.println(7.0 / 2);
        System.out.println(7 / 2.0);

        int total = 10;
        int people = 4;
        System.out.println((double) total / people);
    }
}

Output

3
3.5
3.5
2.5

Common mistake: 1 / 2 is 0 in Java, not 0.5! Make one of the numbers a double when you want decimals.

The remainder operator %

% (called modulo) gives what is left over after dividing:

Think of it like this: You share 17 sweets between 5 friends. Each gets 17 / 5 = 3 sweets, and 17 % 5 = 2 sweets are left over.

public class Main {
    public static void main(String[] args) {
        System.out.println(17 / 5);
        System.out.println(17 % 5);
        System.out.println(10 % 2);
        System.out.println(11 % 2);
    }
}

Output

3
2
0
1

Tip: n % 2 is 0 for even numbers and 1 for odd numbers. You'll use this trick a lot.

Order of operations

Like in school maths, *, / and % happen before + and -. Use brackets to change the order:

public class Main {
    public static void main(String[] args) {
        System.out.println(2 + 3 * 4);
        System.out.println((2 + 3) * 4);
    }
}

Output

14
20
HOME LABS COMMUNITY DASHBOARD