IntScription()
← Back to Notes Home

What is Type Casting ?

It’s when you assign a value of one primitive data type to another

  • Widening Casting (automatically): Converting a smaller type to larger type size byte -> short -> char -> int -> long -> float -> double
public class test(){
  public static void main(String[] args){
    int myInt = 9;
    int myDouble = myInt; // automatically changes from int                                to double
    System.out.println(myInt); // outputs 9
    System.out.println(myDouble); // outputs 9.0
  }
}
  • Narrowing Casting (manually): Converting a larger type to smaller type size double -> float -> long -> int -> char -> short -> byte
public class test(){
  public static void main(String[] args){
    double myDouble = 9.87d;
    int myInt = (int) myDouble; // manually converts int to                                      double
    System.out.println(myDouble); // outputs 9.78
    System.out.println(myInt); // outputs 9
  }
}