Type Casting in Java
Casting is a process of changing one type value to another type. In Java, we can cast one type of value to another type. It is known as type casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,
- Widening Casting(Implicit)
- Narrowing Casting(Explicitly done)
Widening or Automatic type converion
Automatic Type casting take place when,
- the two types are compatible
- the target type is larger than the source type
Example:
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit type conversion
When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting. If we don't perform casting then compiler reports compile time error.
Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
Double value 100.04
Long value 100
Int value 100
Example of Explicit Conversion
Here, we have one more example of explicit casting, double type is stored into long, long is stored into int etc.
class CastingDemo1
{
public static void main(String[] args)
{
double d = 120.04;
long l = (long)d;
int i = (int)l;
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
Example for Conversion of int and double into a byte
Here, we are converting int and double type to byte type by using explicit type casting.
class Demo2
{
public static void main(String args[])
{
byte b;
int i = 355;
double d = 423.150;
b = (byte) i;
System.out.println("Conversion of int to byte: i = " + i + " b = " + b);
System.out.println("*************************************************");
b = (byte) d;
System.out.println("Conversion of double to byte: d = " + d + " b= " + b);
}
}