Type Conversion
Java can perform type conversion automatically or perform explicit conversion.
Automatic Conversion :
Also known as Widening conversion.
It will take place if the following two conditions are met:
1. Two types are compatible
2. Destination type is larger than the source type
Example : int to float, int to long
Explicit Conversion :
Also known as Narrowing Conversion
Numeric types are not compatible with char or Boolean.
char and Boolean are not compatible with each other
It will take place if the one of the following two conditions are met:
1. Two types are not compatible
2. Destination type is smaller than the source type
Example : int to byte
Example of int to byte explicit conversion:
int a;
byte b;
b = (byte) a; // explicitly casting int to byte as byte is smaller than int data type.
Range of a byte reduced modulo means The remainder of an integer division by the byte’s range
256. If a=257 then b will be 1 as 257%256=1.
Comments
Post a Comment