您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 39

Casting

When we instruct Java to convert a value from one type to anther it is called casting (or type casting).

It is often the case when casting between types that some values are lost / changed due to the different ways types are represented. So, for example, if we cast from a double value to an int, we will lose all of the fractional part of the number. 

If we can imagine a computer system for a car production factory, we wish to know both the precise number of cars produced as a real value (e.g. 200,271.5 cars), and also the number of complete cars we can actually ship out to customers ?customers are unlikely to wish to received incomplete cars! This is illustrated in the program below:

class Cast

{

public static void main( String args[] )

{

int completeCars;

double carsProduced = 200271.5 ;

completeCars = (int) carsProduced;

System.out.println("value in completeCars is: " + completeCars);

}

}

When compiled and run this program produces the following output:

value in completeCars is: 200271

As can be seen, when a double is casted into an intonly the whole number part of the double value is retained.

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg