Java Reference
In-Depth Information
Display 1.3 Precedence Rules
Highest Precedence
First: the unary operators: + , , ++ , −− , and !
Second: the binary arithmetic operators: * , / , and %
Third: the binary arithmetic operators: + and
Lowest Precedence
The actual situation is a bit more complicated than what we have described for
evaluating expressions, but we will not encounter any of these complications in this
chapter. A complete discussion of evaluating expressions using precedence and associa-
tivity rules will be given in Chapter 3.
Integer and Floating-Point Division
When used with one or both operands of type double , the division operator, / ,
behaves as you might expect. However, when used with two operands of type int , the
division operator yields the integer part resulting from division. In other words, inte-
ger division discards the part after the decimal point. So, 10/3 is 3 (not 3.3333 …), 5/
2 is 2 (not 2.5 ), and 11/3 is 3 (not 3.6666 …). Notice that the number is not rounded ;
the part after the decimal point is discarded no matter how large it is.
The operator % can be used with operands of type int to recover the information
lost when you use / to do division with numbers of type int . When used with values
of type int , the two operators / and % yield the two numbers produced when you per-
form the long division algorithm you learned in grade school. For example, 14 divided
by 3 is 4 with a remainder of 2 . The / operation yields the number of times one num-
ber “goes into” another (often called the quotient ). The % operation gives the remain-
der. For example, the statements
integer
division
the % operator
System.out.println("14 divided by 3 is " + (14/3));
System.out.println("with a remainder of " + (14%3));
yield the following output:
14 divided by 3 is 4
with a remainder of 2
The % operator can be used to count by 2's, 3's, or any other number. For example,
if you want to do something to every other integer, you need to know if the integer is
even or odd. Then, you can do it to every even integer (or alternatively every odd inte-
ger). An integer n is even if n%2 is equal to 0 and the integer is odd if n%2 is equal to 1 .
Similarly, to do something to every third integer, your program might step through all
integers n but only do the action when n%3 is equal to 0 .
 
Search WWH ::




Custom Search