# Explicit Casting?

• July 14th, 2013, 04:54 PM
syregnar86
Explicit Casting?
SITUATION:

Reading my text book and it says that implicit casting will work if the result of a casting fits into the target variable. If it doesn't I'm told to use explicit tasking.

EXAMPLE (IMPLICIT)

byte b = 'a';
int i = 'a';

EXAMPLE (EXPLICIT)

byte b = (byte)'\uFFF4';

QUESTION:

Data types have a range. Therefore, if a value is not within this range how on earth can it be assigned explicitly at all? I just do not understand this completely.
• July 14th, 2013, 05:23 PM
GregBrannon
Re: Explicit Casting?
Range and size can be (usually are?) related. The type byte allows values from -128 to 127. 'a' = 97 and 'z' = 122 so both will fit in a byte variable using implicit casting. Try to implicitly cast the char = 128 into a type byte, and you'll get an error. Explicitly cast char = 128 int a byte, and what do you get?
• July 14th, 2013, 05:41 PM
syregnar86
Re: Explicit Casting?
It tells me there is a loss of precision. So is this the same as rounding???

Attachment 2194
• July 14th, 2013, 06:44 PM
helloworld922
Re: Explicit Casting?
It's not quite the same as rounding, though it is somewhat related because you just can't represent some values in a "smaller" type.

The fact is modern computers represent numbers in binary. A "smaller" type simply has less bits. According to the 5.1.3 of the Java Language Specifications, down-casting for integral types (byte, char, short, int, long) takes the n least significant bits, where n is the number of bits in the target value.

So:

Code java:

```// this is hexedecimal so I don't have to write 32-bit values in binary :P int(0x12345678) = byte(0x78) int(0x12345678) = short(0x5678)```

In addition to this, Java uses two's compliment to represent signed types.

So even though int(0x7FFF) = byte(0xFF), the integral value of the int is 32767, and the integral value of the byte is -1!

In Java you must make an explicit case from int to byte because of this. The reasoning is that this behavior is usually not expected (in what world does 32767 even come close to equal -1?), but it is very important to be able to make this case because the int value may not necessarily be out of range (int(1) = byte(1)), and there are many useful things you can do using bit-fields and bit-twiddling (mucking with the bits), though I have qualms with using Java with bit-fields and bit-twiddling.