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.

Conversions between primitive types
Previous     Next

Tutorial Home


Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: