-
Java provides 5 math operators as listed below:
+ |
Addition, as well as unary + |
- |
Subtraction, as well as unary - |
* |
Multiplication |
/ |
Floating point and integer division |
% |
Modulus, remainder of integer or floating point division |
The numerical result and data type of the answer depends on the type of operands used in a problem.
- For all the operators, if both operands are integers, the result is an integer. Examples:
2 + 3 -> 5 |
9 - 3 -> 6 |
4 * 8 -> 32 |
11/2 -> 5 |
Notice that 11/2 is 5, and not 5.5. This is because ints work only with whole numbers. The remaining half is lost in integer division.
- If either of the operands is a double type, the result is a double type. Examples:
2 + 3.000 -> 5.000
25 / 6.75 -> 3.7037
11.0 / 2.0 -> 5.5
When an integer and a double are used in a binary math expression, the integer is promoted to a double value, and then the math is executed. In the example 2 + 3.000 -> 5.000
, the integer value 2 is promoted to a double (2.000
) and then added to the 3.000
.
- The modulus operator (
%
) returns the remainder of dividing the first operand by the second. For example:
10 % 3 -> 1 |
2 % 4 -> 2 |
16 % 2 -> 0 |
27.475 % 7.22 -> 5.815 |
- Changing the sign of a value can be accomplished with the negation operator (-), often called the unary (-) operator. A unary operator works with only one value. Applying the negation operator to an integer returns an integer, while applying it to a double returns a double value. For example:
-(67) -> -67 |
-(-2.345) -> 2.345 |
- To obtain the answer of 5.5 to a question like 11/2, we must cast one of the operands.
(double)11/2 |
results in 5.5 |
The casting operators are unary operators with the following syntax:
(type) operand
The same effect can also result from simply
11.0/2