Java Reference
In-Depth Information
Most of the expressions in Java use operators such as “*”. Operators are special symbols
used for mathematical functions, some types of assignment statements, and logical com-
parisons.
Arithmetic
Five operators are used to accomplish basic arithmetic in Java, as shown in Table 2.3.
TABLE 2.3
Arithmetic Operators
Operator
Meaning
Example
2
Addition
+
3 + 4
Subtraction
-
5 - 7
Multiplication
*
5 * 5
Division
/
14 / 7
Modulus
%
20 % 7
Each operator takes two operands, one on either side of the operator. The subtraction
operator also can be used to negate a single operand, which is equivalent to multiplying
that operand by 1.
One thing to be mindful of when performing division is the kind of numbers being used.
If you store a division operation into an integer, the result will be truncated to the next
lower whole number because the int data type can't handle floating-point numbers. As
an example, the expression 31 / 9 results in 3 if stored as an integer.
Modulus division, which uses the % operator, produces the remainder of a division opera-
tion. The expression 31 % 9 results in 4 because 31 divided by 9, with the whole number
result of 3, leaves a remainder of 4.
Note that many arithmetic operations involving integers produce an int regardless of the
original type of the operands. If you're working with other numbers, such as floating-
point numbers or long integers, you should make sure that the operands have the same
type you're trying to end up with.
Listing 2.2 contains a class that demonstrates simple arithmetic in Java.
LISTING 2.2
The Full Text of Weather.java
1: public class Weather {
2: public static void main(String[] arguments) {
3: float fah = 86;
4: System.out.println(fah + “ degrees Fahrenheit is ...”);
 
Search WWH ::




Custom Search