Tuesday, 6 June 2023

Type Casting in Java

Type Casting

Converting one data type into another data type is called casting. Type cast operator is used to convert one data type into another data type. Data type represents the type of the data stored into a variable. There are two kinds of data types:

 1. Primitive data type: Primitive data type represents singular values.

e.g.: byte, short, int, long, float, double, char, boolean.

Using casting we can convert a primitive data type into another primitive data type. This is done in two ways, widening and narrowing.

a) Widening: Converting a lower data type into higher data type is called widening.

e.g.: char ch = 'a';

              int n = (int ) ch;

e.g.: int n = 12;

                    float f = (float) n;

      b) Narrowing: Converting a higher data type into lower data type is called narrowing.

            e.g.:  int i = 65;

                    char ch = (char) i;

e.g.: float f = 12.5;

        int i = (int) f;

 2. Referenced data type: Referenced data type represents multiple values.

e.g.: class, String

Using casting we can convert one class type into another class type if they are related by means of inheritance.

a)  Generalization: Moving back from subclass to super class is called generalization or widening or upcasting.

b)  Specialization: Moving from super class to sub class is called specialization or   

narrowing or downcasting.

 

e.g.: Program to convert one class type into another class type.

// conversion of one class type into another class type

class One

{          void show1()

{          System.out.println ("One's method");

}

}

class Two extends One

{          void show2()

{          System.out.println ("Two's method");

}

}

class Ex3

{          public static void main(String args[])

{

/* If super class reference is used to refer to super class object then only super class members are available to programmer. */

                        One ob1 = new One ();

ob1.show1 ();


/* If sub class reference is used to refer to sub class object then super class members as well as sub class members are available to the programmer. */

                        Two ob2 = new Two();

ob2.show1();

ob2.show2();

 

/* If super class reference is used to refer to sub class object then super class methods are available, sub class methods are not available unless they override super class methods */

One ob3 = (One) new Two();             // Generalization

 ob3.show1();


/* It is not possible to access any methods if we use subclass object to refer to super class as above */

Two ob4 = (Two) new One();

ob4.show1();

ob4.show2();

 

// Specialization

One ob5 = (One) new Two();

 Two ob6 = (Two) ob5;

ob6.show1();

ob6.show2(); 

} 

}

 Note: Using casting it is not possible to convert a primitive data type into a referenced data type and vice-versa. For this we are using Wrapper classes.


No comments:

Post a Comment