Java Type Casting


Java Type Casting

Java is fairly common to assign a value of one type to a variable of another type. If the two types are compatible, then java will perform the conversion automatically.

There are two types of castings available in Java. They are-


Automatic Type Casting

Program
public class Main
{
    public static void main(String[] args) {
     int IntegerNumber = 100;
     float FloatNumber = IntegerNumber; //type casting int to float
  
     System.out.println("IntegerNumber = " + IntegerNumber);
     System.out.println("FloatNumber = " + FloatNumber);
  }
}
Run

Other examples of Automatic Type Casting

Example Run
byte -> short Run
short -> int Run
int -> long Run
long -> float Run
float -> double Run

Manual Type Casting

Program
public class Main
{
   public static void main(String[] args) {
    float a = 1000.38233F;
    int b =(int) a; //type casting float to double
	  
    System.out.println("a = "+a);
    System.out.println("b = "+b);
   }
}
Run

Other examples of Manual Type Casting

Example Run
double -> float Run
float -> long Run
long -> int Run
int -> char Run
char -> short Run
short -> byte Run