|
Java in some rare cases does automatically changes a wider type into narrower type. This happens particularly when you assign an integral literal to data type byte, short or char. We saw earlier (in chapter 7) that the integral literals are always of type int. So you will obviously expect the following code to throw an error:
byte b = 10; // valid
In fact, the above code is valid. The integral literal 10 is of type int. But Java automatically converts its type into byte. This is called as a narrowing conversion as Java is automatically converting the wider data type int to a narrower data type byte. Java also performs this type of narrowing conversion when you are assigning integral literals to data types short and char. Therefore following code represents valid assignments:
char c = 10; // valid
short s = 10; // valid
Remember that the narrowing conversion occurs only when the integral literal fits in the data type’s range. If it does not fit, there could be a loss of information and hence Java compiler flags an error. For example, following code will not compile as 128 is out of range for byte variable:
byte b = 128; // Compile-time error
short s = 128; // Valid as 128 is within range of short
Note that this type of narrowing conversion happens only when the assigned value is an integral literal. If the assigned value is an expression, the narrowing conversion does not take place. Hence, following code doe not compile:
int i = 10;
byte b = i; //Compile-time Error
The variable i is an int variable. Since it can hold any int value at runtime, the compiler cannot be sure whether it will be within a range of byte. To be safe, it flags an error.
|
|
The narrowing conversion does not take place in case of
floating-point literals. The floating-point literals are double by default.
If you assign them to a floating-point variable, Java compiler flags an error
even when the value lies within float’s range. For example, following
code will not compile, as the literal 2.5 is of type double by default: |