TYPE CASTING




Type casting
  • Converting one data type into another type is known as type casting.
  • There are three types of type casting we have
    1. Primitive type casting
    2. Non primitive type casting
    3. Primitive to non primitive type casting


Primitive type casting:
  • Converting from one primitive data type to another primitive data type is known as primitive type casting
  • There are two types of primitive type casting
    • Widining
    • Narrowing

Widining:
  • Conversion from one smaller primitive data type into the bigger primitive data type is known as widining.
  • Widining happens automatically by the compiler.
  • In there is no data loss hence it is known as implicit (Internal) type casting.

Program

  1. class TypeCasting
  2. {  
  3. public static void main(String [] args)
  4. {
  5. byte b= 24;
  6. byte a= b;
  7. {
  8. System.out.println(a);
  9. }
  10. }

Output:

24                                                          
                                                              
                                                              


Narrowing:
  • Conversion from one bigger primitive data type to a smaller primitive data type is known as narrowing.
  • We can actually narrowing with the help of type cast operator.
  • In narrowing we will be e having data loss hence it is also known as explicit type casting.


Type cast operator:
  • Conversion from one data type to another data type is respective of size.
Syntax 

  date type varname = (converting data type) vaiable/value 

  1. class TypeCastOperator
  2. {  
  3. public static void main(String [] args)
  4. {
  5. int b= 1024;
  6. byte a=(byte) b;
  7. {
  8. System.out.println(a);
  9. }
  10. }

Output:

1024