posted 19 years ago
Hi Ravinder,
Casts can be implicit or explicit. An implicit cast means you don't have to write code for the cast; the conversion happens automatically. Typically, an implicit cast happens when you're doing a widening conversion. In other words, putting a smaller thing (say, a byte) into a bigger container (like an int). Remember those "possible loss of precision" compiler errors we saw in the assignments section? Those happened when we tried to put a larger thing (say, a long) into a smaller container (like a short). The large-value-into-small-container conversion is referred to as narrowing and requires an explicit cast, where you tell the compiler that you're aware of the danger and accept full responsibility.
But now you will find it weird that why byte is holding the int value.
The following is legal,
byte b = 27;
but only because the compiler automatically narrows the literal value to a byte. In other words, the compiler puts in the cast. The preceding code is identical to the following:
byte b = (byte) 27; // Explicitly cast the int literal to a byte
It looks as though the compiler gives you a break, and lets you take a shortcut with assignments to integer variables smaller than an int.
Similarily it is true for byte char and short. But when you cast the long to byte the compiler do not narrow the literal automaticaly by putting cast thats why you get the compiler error.
Gaurav