❌

Reading view

There are new articles available, click to refresh the page.

Type casting

What is typecasting ?

  • Type typecasting is a converting one data type to another data type in java ,used either compiler or programmer , for example: converting int to double, double to int.
  • Type casting also know as type conversion.

Types of casting:-

  • widening type casting(java)
  • Narrowing type casting(programmer)

Primitive typecasting:-

widening type casting(java):-

widening type casting is also know as implicitly type conversion like ,The process converting smaller type (int) to lager type,This job done by compiler automatically( Java compiler uses the predefined library function for transforming the variables). The conversion done time compile time.

Never data loss.

Hierarchy:-

byte->short->char->int->long->float->double. 

Example:-

/widening type casting
public class Tester {

    public static void main(String[] args) {

        int num1 =501;
        double num2=2.5;
        double sum = num1 +num2; // typeconvertion done by java.

        System.out.println("The sum of "+num1+ " and "+num2+" is "+sum);

    }

}


Narrow type casting:-

Narrow type casting is also know explicit type casting or explicit type conversion.this conversion done by programmer manually,this type conversion converting larger type to smaller type.if do not do manually compile time error will occur.

Hierarchy:-

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

Example:-

public class Narrowing_Test2 {

    public static void main(String[] args) {

        int num =501;

        //type casting int to double
        double doubleNum = (double) num;

        System.out.println("Type casting int to double: "+doubleNum);

        //type casting   double to  int
       // possible  data loss in narrowing casting , because is can  not hold larger data to small type data type                           
        int   num2 = (int) doubleNum;

        System.out.println("Type casting   double to int: "+num2);


    }

}
  • Can not auto convert(not compatible ) to/from boolean with number types.

  • char can be cast to/from int,but explicitly.

we will see explicit Upcasting and Downcasting in inheritance:-

In inheritance(object typecasting):-

what is Upcasting?

  • Converting a child class object to parent class reference.
  • Done implicitly (automatically)
  • No typecasting needed
  • Safe and not possible data loss
 Dog d = new Dog(); //child class object 
Animal a = d;  // Upcasting (automatic)

what is Downcasting?

  • Converting a parent class reference to a child class reference.
  • Done explicitly(manually)
  • you must need type cast.
  • Error occurred if do not done manually throw the ClassCastException.
Animal a = new  Dog (); // upcasting
Dog d = (Dog) a ; //downcasting (manual)
❌