Type Conversion and Casting

Premium Content - Free Preview

Type Conversion

Sometimes you need to convert between different primitive types. For example, you may wish to store integers in floating-point types so they can handle decimal values.

In many cases, you can assign the values of one variable type to another variable type:

int i = 5;
double d = i;

This will print out:


This is because d will be assigned the 5 and will store it as a decimal value.

Java will automatically convert types as long as the types are compatible and the following condition is met:

  • The type being assigned (on the left) is larger than the type being copied (on the right). For example, a double and long are larger than an int. This is why the d can accept the value of i above without issue.


What if you want to assign a double or long to an int? Java will not automatically convert it, since an int cannot hold all their possible values. To convert a larger type to a smaller type, you need to explicitly "cast" it. This is a way of telling Java "I understand its going to a smaller type, don't worry". The cast has this general syntax:

newValue = (newValueType) originalValue;

To cast a number to an int you would use (int). In the code below two numbers are cast to ints:

End of Free Content Preview. Please Sign in or Sign up to buy premium content.


Contact Us
Sign in or email us at [email protected]