Page 115 - Introduction to Programming with Java: A Problem Solving Approach
P. 115
3.19 TypeCasting 81
1 public class TestOperators
2{
3
public static void main(String[] args)
4{
5
int x;
int y = 2;
double z = 3.0;
x = 5;
System.out.println("x + y + z = " + (x + y + z));
x += y;
y++;
z--;
z *= x;
System.out.println("x + y + z = " + (x + y + z));
// end main
6
7
8
9
10
11
12
13
14
15
16
}
17
} // end class TestOperators
Trace:
line#
x
y
z
output
5
?
6
7
3.0
9
5
10
x y z 10.0
11
7
12
3
13
2.0
14
14.0
15
x y z 24.0
Apago PDF Enhancer
2
Figure 3.8 TestOperators program and its trace
Cast Operator
In writing a program, you’ll sometimes need to convert a value to a different data type. The cast operator can be used to perform that sort of conversion. Here’s the syntax:
(<type>) <value>
As shown above, a cast operator consists of a data type inside parentheses. You should place a cast operator at the left of the value that you’d like to convert.
c
c
a
a
s
s
t
to
op
pe
er
r
a
a
t
to
o
r
r