Casting is the act of converting one of the variables into another. There are two types of casting in Java:
Before learning to cast variables, you should know the type hierarchy:
Implicit casting is when you assign the value of the old variable, to the new variable, without any additional code. However, this is only valid if a narrower variable is being converted into a wider one (e.g. converting int
into double
). Polymorphism, when an object of a child (narrower) class is referred to by a reference variable of the parent (wider) class, is an example of this.
byte i = 10;long newType = i;
Explicit casting is the opposite of implicit casting. It is used when we have to convert a wider variable to a narrower one; but this time, we have to explicitly write the type we are converting to in ()
. Otherwise, a compile-time error will occur.
double d = 50;int x = (int)d;
Free Resources