Arithmetic operators
Arithmetic operators perform mathematical operations on numeric types.
| Operator | Description | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder) | a % b |
Examples:
int a = 10, b = 3;System.out.println(a + b); // 13System.out.println(a - b); // 7System.out.println(a * b); // 30System.out.println(a / b); // 3 (integer division)System.out.println(a % b); // 1Division with floating‑point:
double x = 10.0, y = 3.0;System.out.println(x / y); // 3.3333333333333335Division by zero:
- Integer division by zero throws
ArithmeticException. - Floating‑point division by zero yields
InfinityorNaN.
// int zeroDiv = 10 / 0; // throws ArithmeticExceptiondouble inf = 10.0 / 0.0; // InfinityModulus with negative numbers: The sign of the result is the sign of the dividend.
System.out.println(10 % 3); // 1System.out.println(10 % -3); // 1System.out.println(-10 % 3); // -1