Page 109 - Introduction to Programming with Java: A Problem Solving Approach
P. 109

                3.15 Arithmetic Operators 75 double and then performs floating-point division on the two floating-point values. The expression evalu-
ates to 1.25.
Integer Division
When the JVM performs division on integers, it performs “grade school division.” We call it grade school division because Java’s integer division works the same as the division you did by hand in grade school. Remember how you calculated two values for each division operation? You calculated a quotient and also a remainder. Likewise, Java has the ability to calculate both a quotient and a remainder when integer divi- sion is called for. But Java doesn’t calculate both values simultaneously. If Java’s / operator is used, then the quotient is calculated. If Java’s % operator is used, then the remainder is calculated. The % operator is more formally called the modulus operator. Note these examples:
7 / 2⇒3 7 % 2⇒1
These correspond to the equivalent grade school arithmetic notation:
3
2 􏰀7 -6
We’ll give you many expression evaluation problems like this. As a sanity check, we recommend that
you verify at least some of the calculated results by executing the expressions on a com-
    q
q
u
u
o
o
t
t
i
i
e
en
nt
t
    1
r
r
e
e
m
m
a
a
i
in
n
d
de
e
r
r
     puter. To execute the expressions, embed the expressions into print statements, embed the
Apago PDF Enhancer
Print details to see what com- puter does.
  print statements into a test program, and run the test program. For example, to execute the above expressions, use the TestExpressions program in Figure 3.6.
 public class TestExpressions
{
public static void main(String[] args)
{
}
System.out.println("7 / 2 = " + (7 / 2));
System.out.println("7 % 2 = " + (7 % 2));
System.out.println("8 / 12 = " + (8 / 12));
System.out.println("8 % 12 = " + (8 % 12));
// end main
} // end class TestExpressions
Output:
7/2= 3
7%2= 1
8 / 12 = 0
8 % 12 = 8
 Figure 3.6 TestExpressions program and its output





































   107   108   109   110   111