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.
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)
}
}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
}
}