Convert / cast between primitive data types

Certain things need to be considered when doing certain conversions. All of the primitive types can be converted to another type except for the boolean type.
There are two different types of conversions. A widening conversion occurs when converting from a smaller type to a larger, for example converting from and integer, which is stored as a 32-bit value, to a long which is stored as a 64-bit value.
The other type is the narrowing conversion, which is the opposite. Narrowing conversion isn’t allowed by default in Java, so you need to explicitly tell the compiler that it is ok to do this kind of conversion.

When converting from floating-point types to integer types the decimals simply disappear. It is not rounded to nearest integer.
To do a proper rounding you should use any of the methods of the Math class.

The table below shows which conversions that can be done.
The value ‘No’ tells that a conversion isn’t possible, ‘yes’ says that it is a widening conversion and no casting needs to be done.
The value ‘Cast’ tells that it’s a narrowing conversion so it needs to be explicit.

Conversion between primitive data types

Search for more Java info on this site here:
Custom Search

Please type any questions here.