Casting Between Data Types

   

Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 2.  Keywords, Data Types, and Variables


Does this mean that the result of your operations must be the data type of the largest data type in the operation? What if you, as the programmer, have knowledge of the nature of the data and can ensure that the data will not be lost?

Java offers a mechanism for overriding the compiler called casting. Casting tells the compiler to convert the data to the specified type even though it might lose data. By casting you are assuring the compiler that either data will not be lost, or if it is, that you will not care. Casting is performed by prefixing the variable or value by the desired data type enclosed in parentheses:

 datatype variable = ( datatype )value; 

For example:

 int i = 10;  short s = ( short )i;  long l = 100;  byte b = ( byte )l; 

Be sure that you do this with caution because the side effect of casting a variable to a narrower data type can result in the loss of data as you saw earlier.


       
    Top
     



    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net