Converting Primitives
suggest changeIn Java, we can convert between integer values and floating-point values. Also, since every character corresponds to a number in the Unicode encoding, char types can be converted to and from the integer and floating-point types. boolean is the only primitive datatype that cannot be converted to or from any other primitive datatype.
There are two types of conversions: widening conversion and narrowing conversion.
A widening conversion converts a value to a datatype that can hold a wider range. It can still lose precision: an int may not survive conversion to float, and a long may not survive conversion to float or double.
A narrowing conversion converts a value to a datatype that occupies fewer bits. Magnitude can be lost in this case.
Java performs widening conversions automatically. But if you want to perform a narrowing conversion (if you are sure that no data loss will occur), then you can force Java to perform the conversion using a language construct known as a cast.
Widening Conversion:
int a = 1;
double d = a; // valid conversion to double, no cast needed (widening)
Narrowing Conversion:
double d = 18.96;
// int b = d; // invalid: narrowing needs a cast
int b = (int) d; // truncates toward zero, so b == 18