Type Conversion and Casting
Premium Content - Free Preview
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; System.out.println(d);
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
longare larger than an
int. This is why the
dcan accept the value of
iabove without issue.
What if you want to assign a
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: