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 divisionThe 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 -> 59 - 3 -> 64 * 8 -> 3211/2 -> 5Notice 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.00025 / 6.75 -> 3.703711.0 / 2.0 -> 5.5When 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 -> 12 % 4 -> 216 % 2 -> 027.475 % 7.22 -> 5.815Changing 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.345To 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.5The casting operators are unary operators with the following syntax:
(type) operandThe same effect can also result from simply
Last modified: December 12, 2022
Back to Assignment Statements