Arithmetic Operators in Java – Explained with Examples
Arithmetic operators perform basic maths on numbers: addition, subtraction, multiplication, division and remainder. They look exactly like school maths, but a few Java rules, such as integer division, type promotion and overflow, regularly surprise beginners.
This tutorial covers each arithmetic operator, the rules behind division and remainders, how Java chooses the result type, and practical examples you will use again and again.
1. The Five Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition (also string concatenation) | 20 + 6 | 26 |
- | Subtraction | 20 - 6 | 14 |
* | Multiplication | 20 * 6 | 120 |
/ | Division | 20 / 6 | 3 (integers) or 3.33… (decimals) |
% | Remainder (modulus) | 20 % 6 | 2 |
public class ArithmeticBasics {
public static void main(String[] args) {
int a = 20, b = 6;
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) + " (integer division)");
System.out.println("a % b = " + (a % b) + " (remainder)");
double x = 20, y = 6;
System.out.println("x / y = " + (x / y) + " (double division)");
System.out.printf("x / y = %.2f (formatted)%n", x / y);
}
}
a + b = 26 a - b = 14 a * b = 120 a / b = 3 (integer division) a % b = 2 (remainder) x / y = 3.3333333333333335 (double division) x / y = 3.33 (formatted)
2. Integer Division and Remainders
When both operands are integers, / performs integer division: the result is truncated toward zero, and the fraction is thrown away. The % operator gives what was thrown away. These rules also apply to negative numbers and division by zero:
public class DivisionRules {
public static void main(String[] args) {
// Integer division truncates toward zero
System.out.println("7 / 2 = " + (7 / 2) + ", -7 / 2 = " + (-7 / 2));
// The remainder takes the sign of the left operand
System.out.println("7 % 3 = " + (7 % 3) + ", -7 % 3 = " + (-7 % 3) + ", 7 % -3 = " + (7 % -3));
System.out.println("Math.floorMod(-7, 3) = " + Math.floorMod(-7, 3));
// % also works with decimals
System.out.println("5.5 % 2 = " + (5.5 % 2));
// Division by zero
System.out.println("10.0 / 0 = " + (10.0 / 0) + ", 0.0 / 0 = " + (0.0 / 0));
try {
System.out.println(10 / 0);
} catch (ArithmeticException e) {
System.out.println("10 / 0 -> ArithmeticException: " + e.getMessage());
}
}
}
7 / 2 = 3, -7 / 2 = -3 7 % 3 = 1, -7 % 3 = -1, 7 % -3 = 1 Math.floorMod(-7, 3) = 2 5.5 % 2 = 1.5 10.0 / 0 = Infinity, 0.0 / 0 = NaN 10 / 0 -> ArithmeticException: / by zero
-7 / 2is-3, not-4: Java truncates toward zero.- The sign of
%follows the left operand. UseMath.floorMod()when you always want a non-negative result, for example for wrapping around a clock or an array. - Integer division by zero throws
ArithmeticException; floating-point division by zero givesInfinityorNaN(not a number).
3. Result Types and Type Promotion
The type of an arithmetic result depends on its operands, following these rules:
- If either operand is
double, the result isdouble. - Otherwise, if either is
float, the result isfloat. - Otherwise, if either is
long, the result islong. - Otherwise the result is
int, even forbyte,shortandcharoperands.
public class TypePromotion {
public static void main(String[] args) {
byte b1 = 10, b2 = 20;
// byte sum = b1 + b2; // compile error: int cannot be converted to byte
int sum = b1 + b2; // byte, short and char are promoted to int
byte castSum = (byte) (b1 + b2); // or cast explicitly
System.out.println("sum = " + sum + ", castSum = " + castSum);
int count = 3;
double avg = 10 / count; // int division happens first!
double avgOk = 10.0 / count; // one double operand -> double division
System.out.println("avg = " + avg + ", avgOk = " + avgOk);
long big = 1_000_000 * 3_000; // overflow: computed as int
long bigOk = 1_000_000L * 3_000; // long arithmetic
System.out.println("big = " + big + ", bigOk = " + bigOk);
char c = 'a';
System.out.println("'a' + 2 = " + (c + 2) + " -> " + (char) (c + 2));
}
}
sum = 30, castSum = 30 avg = 3.0, avgOk = 3.3333333333333335 big = -1294967296, bigOk = 3000000000 'a' + 2 = 99 -> c
byte + byteis anint, so storing it back in abyteneeds a cast.10 / countis computed as an integer before being stored in adouble, so the fraction is already lost.1_000_000 * 3_000overflows because both literals areint; oneLsuffix makes the whole calculationlong.
4. The + Operator with Strings
If either operand of + is a String, Java converts the other one to text and joins them. Evaluation is left to right, so:
System.out.println(1 + 2 + " apples"); // 3 apples
System.out.println("apples: " + 1 + 2); // apples: 12
System.out.println("apples: " + (1 + 2));// apples: 3
5. Practical Examples
Integer division and % together solve many everyday problems: converting units, checking divisibility and extracting digits.
public class PracticalArithmetic {
public static void main(String[] args) {
// 1. Seconds to hours, minutes and seconds
int totalSeconds = 7385;
int hours = totalSeconds / 3600;
int minutes = (totalSeconds % 3600) / 60;
int seconds = totalSeconds % 60;
System.out.printf("%d seconds = %dh %dm %ds%n", totalSeconds, hours, minutes, seconds);
// 2. Even or odd
for (int n : new int[] {14, 27}) {
System.out.println(n + " is " + (n % 2 == 0 ? "even" : "odd"));
}
// 3. Sum of the digits of a number
int number = 4825, digitSum = 0;
for (int n = number; n > 0; n /= 10) digitSum += n % 10;
System.out.println("Digit sum of " + number + " = " + digitSum);
// 4. Simple interest
double principal = 50_000, rate = 7.5, years = 3;
System.out.println("Interest = " + principal * rate * years / 100);
}
}
7385 seconds = 2h 3m 5s 14 is even 27 is odd Digit sum of 4825 = 19 Interest = 11250.0
6. Overflow and Precision
- Integer overflow wraps around silently. Use
Math.addExact(),Math.multiplyExact()and similar methods to get an exception instead, or uselongorBigInteger. - Floating-point values are approximate.
0.1 + 0.2is0.30000000000000004. UseBigDecimalfor money and other exact decimal calculations. - Round explicitly with
Math.round(), or format output withprintf("%.2f", value).
7. Beyond the Operators: the Math Class
For powers, roots and other functions, Java uses methods instead of operators: Math.pow(2, 10) (there is no ** or ^ power operator; ^ is bitwise XOR), Math.sqrt(16), Math.abs(-5), Math.max(a, b) and Math.round(2.6). See Math class in Java.
8. Common Mistakes
- Expecting
5 / 2to be2.5. - Calculating an average with integers:
sum / countloses the fraction. - Using
^for powers. - Forgetting that
%can be negative. - Multiplying large
intvalues without switching tolong. - Concatenating numbers into a string before adding them.
9. Summary
- Java's arithmetic operators are
+,-,*,/and%. - Integer division truncates toward zero;
%gives the remainder with the sign of the left operand. - Operands are promoted to at least
int; the widest operand type decides the result type. - Integer division by zero throws an exception; floating-point division gives
InfinityorNaN. - Watch for overflow and floating-point precision.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What are arithmetic operators in Java?
Operators that perform basic mathematical calculations: + (addition), - (subtraction), * (multiplication), / (division) and % (remainder).
Q2. What is the difference between / and %?
/ gives the quotient and % gives the remainder. For 17 / 5 the result is 3, and 17 % 5 is 2.
Q3. Why does 5 / 2 return 2?
Both operands are int, so Java performs integer division and discards the fraction. Use 5 / 2.0 or (double) 5 / 2 to get 2.5.
Q4. What happens when you divide by zero in Java?
Integer division by zero throws ArithmeticException: / by zero. Floating-point division by zero returns Infinity, -Infinity or NaN without an exception.
Q5. Can the modulus result be negative?
Yes. The result has the same sign as the left operand: -7 % 3 is -1. Math.floorMod(-7, 3) returns 2 if you need a non-negative result.
Q6. Does % work with decimal numbers?
Yes. 5.5 % 2 is 1.5. It works with float and double as well as integer types.
Q7. Why does byte + byte give an int?
Java promotes byte, short and char operands to int before arithmetic. The result is an int, so assigning it to a byte requires a cast.
Q8. How do I calculate a power in Java?
Use Math.pow(base, exponent), which returns a double. Java has no power operator; ^ is bitwise XOR.
Q9. How do I round the result of a division?
Use Math.round(x) for the nearest whole number, Math.floor()/Math.ceil() to round down or up, or format output with String.format("%.2f", x).
Q10. What is integer overflow?
When a result exceeds the range of its type and wraps around, for example Integer.MAX_VALUE + 1 becomes Integer.MIN_VALUE. Java does not report it unless you use Math.addExact() and similar methods.
Q11. What is NaN?
"Not a Number", the result of undefined floating-point operations such as 0.0 / 0 or Math.sqrt(-1). Check for it with Double.isNaN(x), because NaN == NaN is false.
Q12. Why is 0.1 + 0.2 not equal to 0.3?
Many decimal fractions cannot be stored exactly in binary floating-point, so small rounding errors appear. Use BigDecimal for exact decimal arithmetic.
Q13. How do I check if a number is even?
Use n % 2 == 0. This works for negative numbers too, because the remainder is 0 for even numbers regardless of sign.
Q14. Is + only for numbers?
No. If either operand is a String, + concatenates: "Total: " + 5 becomes "Total: 5".
Q15. What is the precedence of arithmetic operators?
*, / and % have higher precedence than + and -. Operators of the same level are evaluated left to right. Parentheses override both rules.
Q16. How do I get the last digit of a number?
Use n % 10. To remove the last digit, use n / 10. Repeating both in a loop processes every digit.
Q17. Can arithmetic operators be used with char?
Yes. A char is a 16-bit number, so 'a' + 1 is 98. Cast back to char to get 'b'.
Q18. Which is better for money: double or BigDecimal?
BigDecimal, created from strings such as new BigDecimal("19.99"). Alternatively store amounts as whole cents in a long.
Q19. What is the difference between -7 / 2 in Java and in Python?
Java truncates toward zero, giving -3. Python's // floors, giving -4. Use Math.floorDiv(-7, 2) in Java to get Python's behaviour.
Q20. Can I use arithmetic operators on wrapper objects like Integer?
Yes. Java unboxes them automatically. Be careful with null: unboxing a null Integer throws NullPointerException.