Java Reference
In-Depth Information
Self-Test Exercises
(continued)
19. What is the output produced by the following lines of program code?
int
quotient, remainder;
quotient = 7 / 3;
remainder = 7 % 3;
System.out.println("quotient = " + quotient);
System.out.println("remainder = " + remainder);
20. What is the output produced by the following code?
int
result = 11;
result /= 2;
System.out.println("result is " + result);
21. Given the following fragment that purports to convert from degrees Celsius to
degrees Fahrenheit, answer the following questions:
double
celsius = 20;
double
fahrenheit;
fahrenheit = (9 / 5) * celsius + 32.0;
a. What value is assigned to
fahrenheit
?
b. Explain what is actually happening, and what the programmer likely wanted.
c. Rewrite the code as the programmer intended.
Type Casting
A type cast takes a value of one type and produces a value of another type that is Java's
best guess of an equivalent value. We will motivate type casts with a simple division
example.
Consider the expression
9/2
. In Java, this expression evaluates to
4
, because when
both operands are of an integer type, Java performs integer division. In some situations,
you might want the answer to be the
double
value
4.5
. You can get a result of
4.5
by
using the “equivalent” floating-point value
2.0
in place of the integer value
2
, as in the
expression
9/2.0
, which evaluates to
4.5
. But, what if the
9
and the
2
are the values
of variables of type
int
named
n
and
m
. Then,
n/m
yields
4
. If you want floating-point
division in this case, you must do a type cast from
int
to
double
(or another floating-
point type), such as in the following:
double
ans = n/(
double
)m;
The expression
(
double
)m