3.3 Arithmetic Operators
Arithmetic operators encompass the four basic arithmetic operations and the remainder operation commonly dealt with in mathematics.
1. Four Basic Arithmetic Operators (+, -, *, /)
They perform addition, subtraction, multiplication, and division.
A point to note is the division operator (/). In Java, the result of dividing two integers undergoes truncation, always returning an integer. If you wish to obtain a result with decimal points, at least one of the two operands must be a floating-point type.
System.out.println(10 / 4); // Result: 2 (The decimal part is discarded)
System.out.println(10 / 4.0); // Since one side is a double, 10 is automatically converted to 10.0. Result: 2.5
Furthermore, dividing by 0 (e.g., 5 / 0) throws an ArithmeticException at runtime, terminating the program abnormally. However, dividing a floating-point value by 0.0 (e.g., 5.0 / 0.0) does not cause an error but returns Infinity.
2. Remainder Operator (%)
This operator divides the left operand by the right operand and returns the remaining value as the result.
System.out.println(10 % 8); // Outputs 2, which is the remainder of 10 divided by 8
System.out.println(10 % -8); // The sign of the right operand is ignored, so the result is 2 as well
Common Use Cases
The remainder operator is highly useful for determining if a number is even or odd, or for cycling values within a specific range.
- Even/Odd Determination: If
x % 2 == 0it is even; if1it is odd. - Multiple Determination: If
x % 3 == 0it is a multiple of 3.