Java Reference
In-Depth Information
The cast operator consists of placing the data type that the value is being
cast to in parentheses. In this example, f was being cast to an int, so int was
placed in parentheses right before f.
Casting tells the compiler that you are aware of the invalid assignment,
but you want to do it anyway. In the example above, x was assigned to d
by casting, and x will be the value 3. Casting a floating-point number to an
integer data type causes the decimal part of the number to be truncated.
Classroom Q & A
Q: Why would you ever need to assign a double to an int? It seems
like the cast operator would not be used very often.
A: I am not going to say that you will use the cast operator every day,
but it is an important operator in any programming language that
requires strict data typing. If you hand me a floating-point number,
and I want to store it as an integer value, I will need to use the cast
operator.
Q: What if I give you an integer value and you want to store it as
something smaller? In other words, suppose that I give you a short
and you want to store it as a byte. Why would you need to cast
then?
A: I still need the cast operator because you are giving me 16 bits of
data (a short) and I want to store it in eight bits of data (a byte). Any
time you try to store something “bigger” into something “smaller,”
the cast operator is required or the code will not compile.
Q: Why? In C or C++, that would generate only a compiler warning,
not an error.
A: You are getting your first taste of the strictness of Java when it
comes to data types. Besides, there is a possibility of data being
lost, so generating an error draws attention to this, just as when I
take 3.5 and cast it to an int, and the decimal part is lost and I get
3. If the short that you give me is between -128 and 127, casting
it to a byte does not result in the loss of any data. However, if you
give me a short whose value is, say, 250, casting that to a byte
causes the loss of the upper 8 bits of the short, making the value
meaningless. The result of casting 250 to a byte is essentially a
programming error on my part.
Search WWH ::




Custom Search