|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Converting 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. |
//widening conversion, this is ok int i = 0; long l = i; //narrowing conversion, this is not ok long l = 0; int i = l; //since we are sure that the value of the long variable will fit in a variable of type int, //we do a cast of the long variable to an int. This is ok with the compiler. long l = 0; int i = (int) l; |
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. |
![]() |
| Previous | Next | |
Tutorial Home | ||
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site

