Maths symbols
| Symbol | Meaning | Example | Answer |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3 (!) |
% | remainder | 7 % 2 | 1 |
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 / 2is0in Java, not 0.5! Make one of the numbers adoublewhen 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 % 2is 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