Programs calculate constantly: adding prices, counting scores, converting minutes into hours, picking a random number for a game. In Java, calculations are written with operators, the familiar symbols +, -, * and /, plus a few you may not have met before.
Java is strict about types, and that affects arithmetic in ways that surprise beginners. Dividing two whole numbers throws away the decimal part, so 7 / 2 is 3, not 3.5. A number that grows too large for its type wraps around to a negative value without any error. Knowing these rules is the difference between a program that works and one that gives quietly wrong answers.
In this lesson you'll use every arithmetic operator, see how int and double mix, convert between them with casting, update variables with shortcuts like ++ and +=, and use the built-in Math class for rounding, powers, square roots and random numbers.
Arithmetic operators
| Operator | Meaning | int example | double example |
|---|---|---|---|
+ | Add | 7 + 2 is 9 | 7.0 + 2 is 9.0 |
- | Subtract | 7 - 2 is 5 | 7.5 - 2 is 5.5 |
* | Multiply | 7 * 2 is 14 | 1.5 * 2 is 3.0 |
/ | Divide | 7 / 2 is 3 | 7.0 / 2 is 3.5 |
% | Remainder | 7 % 2 is 1 | 7.5 % 2 is 1.5 |
When both sides are integers, / performs integer division and drops the decimal part. If either side is a double, the result is a double. The remainder operator % is perfect for checks like "is this number even?" (n % 2 == 0) or "every third item" (i % 3 == 0).
Casting and precedence
To get a decimal result from two int values, convert one of them to double first with a cast:
int total = 7, people = 2;
double each = (double) total / people; // 3.5
int whole = (int) 9.99; // 9, the decimals are cut offCasting a double to int truncates: it doesn't round. Java follows the usual order of operations: brackets, then *, / and %, then + and -, working left to right. So 2 + 3 * 4 is 14, and (2 + 3) * 4 is 20.
Increment and compound assignment
Changing a variable based on its own value is so common that Java has shortcuts:
| Shortcut | Same as |
|---|---|
count++ | count = count + 1 |
count-- | count = count - 1 |
total += price | total = total + price |
total -= 5 | total = total - 5 |
x *= 2, x /= 2, x %= 3 | x = x * 2 and so on |
++ can go before or after the variable. On its own line there's no difference, but inside a larger expression x++ gives the old value and then adds one, while ++x adds one first. Keep ++ on its own line and you'll never need to remember which.
The Math class and overflow
Java's built-in Math class has the common maths functions:
Math.round(2.5)gives3;Math.floor()rounds down andMath.ceil()rounds up.Math.max(a, b)andMath.min(a, b)choose the larger or smaller value.Math.abs(-4)gives4;Math.pow(2, 10)gives1024.0;Math.sqrt(81)gives9.0.Math.random()gives adoublefrom 0.0 up to, but not including, 1.0.
An int holds values up to about 2.1 billion. Go past that and it overflows, wrapping round to a large negative number without any error. Use long for big numbers like file sizes or milliseconds, and Math.addExact() if you want an exception instead of a silent wrap.
Java Operators Syntax
Operators
a + b a - b a * b a / b a % b
(double) a / b
x++; x--; x += 5; x *= 2;
Math.round(x) Math.max(a, b) Math.min(a, b)
Math.pow(base, exp) Math.sqrt(x) Math.abs(x)
int r = (int) (Math.random() * 6) + 1; // 1 to 6Java Operators Summary
/between two ints drops the decimals; make one side a double for a decimal answer.%gives the remainder, useful for even/odd checks and repeating patterns.(double)and(int)cast between types; casting to int truncates.++,--,+=and friends update a variable using its current value.- The Math class provides round, max, min, abs, pow, sqrt and random; beware int overflow.
Java Operators Examples
Each example shows the code, the output it produces and what each part does.
Converting minutes and checking even numbers
public class Main {
public static void main(String[] args) {
int minutes = 135;
int hours = minutes / 60;
int left = minutes % 60;
System.out.println(minutes + " minutes = " + hours + " h " + left + " min");
for (int n = 1; n <= 5; n++) {
if (n % 2 == 0) {
System.out.println(n + " is even");
}
}
}
}135 minutes = 2 h 15 min
2 is even
4 is evenLine-by-line explanation
- Line 4Integer division gives the whole hours: 2.
- Line 5The remainder is the minutes left over: 15.
- Line 9A number is even when dividing by 2 leaves nothing over.
Averages and casting
public class Main {
public static void main(String[] args) {
int total = 17;
int count = 4;
System.out.println("Wrong average: " + total / count);
System.out.println("Right average: " + (double) total / count);
System.out.println("Rounded: " + Math.round((double) total / count));
System.out.println("Cut off: " + (int) 4.99);
}
}Wrong average: 4
Right average: 4.25
Rounded: 4
Cut off: 4Line-by-line explanation
- Line 6Both values are ints, so the .25 is lost.
- Line 7Casting total to double makes the whole division a double.
- Line 8Math.round rounds 4.25 to the nearest whole number.
- Line 9A cast simply chops off the decimals, even .99.
Scores, shortcuts and Math
public class Main {
public static void main(String[] args) {
int score = 0;
score += 50;
score *= 2;
score -= 15;
score++;
System.out.println("Score: " + score);
int best = Math.max(score, 120);
System.out.println("Best: " + best);
System.out.println("2 to the power 8: " + Math.pow(2, 8));
System.out.println("Square root of 2: " + Math.sqrt(2));
int big = Integer.MAX_VALUE;
System.out.println("Overflow: " + (big + 1));
}
}Score: 86
Best: 120
2 to the power 8: 256.0
Square root of 2: 1.4142135623730951
Overflow: -2147483648Line-by-line explanation
- Lines 4 to 70, then 50, 100, 85 and finally 86.
- Line 10Math.max picks the larger value.
- Lines 12 to 13pow and sqrt always return doubles.
- Lines 15 to 16Adding one to the largest int wraps round to the smallest, with no error.
Common Java Operators Mistakes
Integer division by accident
double half = 1 / 2; // 0.0double half = 1.0 / 2; // 0.5Expecting a cast to round
int stars = (int) 4.7; // 4int stars = (int) Math.round(4.7); // 5Math.round returns a long, so cast it to int if you need an int.
Using double for money
double price = 0.1 + 0.2; // 0.30000000000000004int pence = 10 + 20; // 30
java.math.BigDecimal total = new java.math.BigDecimal("0.1").add(new java.math.BigDecimal("0.2"));Java Operators in Real Projects
Arithmetic in real programs
Games use % to cycle through animation frames and Math.random() for dice and enemy movement. Shops calculate totals and discounts, ideally with BigDecimal. Fitness apps convert seconds into minutes and seconds with / and %. And servers store timestamps as long milliseconds, because an int would have overflowed decades ago.
Java Operators FAQ
Does Java have an exponent operator?
No. The ^ symbol in Java is bitwise XOR, not a power, so 2 ^ 3 is 1. Use Math.pow(2, 10), which returns the double 1024.0. Cast it with (int) or (long) when you need a whole number and the result is within range.
What is the difference between i++ and ++i?
Both add one to i. The difference is the value of the expression itself: i++ gives the old value, and ++i gives the new one. With i = 5, int a = i++; sets a to 5, while int b = ++i; adds one first. On a line by itself, such as count++;, the two are identical.
Why does % give a negative result for negative numbers?
In Java the remainder takes the sign of the left-hand number, so -7 % 3 is -1. If you need a result between 0 and the divisor, for example when wrapping round a circular list, use Math.floorMod(-7, 3), which gives 2.
How can I detect integer overflow?
Use the exact methods in Math: Math.addExact, Math.subtractExact and Math.multiplyExact. They throw an ArithmeticException with the message "integer overflow" instead of silently wrapping round. Switching to long gives a much larger range, and BigInteger has no upper limit.
Why is 0.1 + 0.2 not exactly 0.3 in Java?
double stores numbers in binary, and many decimal fractions such as 0.1 can't be represented exactly in binary. The tiny difference shows up when you print the result. Round when displaying, for example with String.format("%.2f", x), and use BigDecimal or whole cents for money.
Java Operators Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so it prints the remainder of 17 divided by 5.
System.out.println(17 5);
What does this print?
System.out.println(9 / 2);
What does this print?
int x = 10;
x += 5;
x /= 4;
System.out.println(x);
Which expression gives 2.5?
Which line gives a random whole number from 1 to 6?
Java Operators Quiz
5 questions to check what you learned.
What does
%calculate?- A percentage
- Division with decimals
- A power
- The remainder after division
What is
(int) 7.9?- 7
- 8
- 7.9
- An error
What does
Math.pow(3, 2)return?- 6
- 9.0
- 9
- 8.0
What does
count++do?- Doubles count
- Adds count to itself
- Compares count with one
- Adds one to count
What happens when an int goes past its maximum value?
- Java throws an exception
- It becomes a long
- It wraps round to a large negative number
- It stays at the maximum