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;
System.out.println(d);
This will print out:
5.0
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
andlong
are larger than anint
. This is why thed
can accept the value ofi
above without issue.
Casting
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.
Comments
Lukas Dancak
Nov 9, 11:51 AMeasy :) System.out.print((long)a*(long)b*(long)365*(long)24);
thales
Jul 10, 6:28 AMlast long(s) no nescesarry.
long afstand= (long)a *(long)b*8760;
System.out.println(afstand);