Type Casting

Type Casting in Java

1. When you want to convert a value from A type to B type that is called Type Casting.

2. There are two type of Type Casting:

i. Narrowing / Explicit Conversion / Downcasting

ii. Widening / Implicit Conversion / Upcasting

i. Narrowing

  • Narrowing means when you convert a large data type into small data type.
  • When you follow this direction that is called Narrowing.
    double -> float -> long -> int -> short -> byte
  • It is also called Explicit conversion.
  • It is also called Downcasting.
  • Example
                    //this type of conversion is called Explicit or Narrowing.
                    int i=10;
                    byte b=(byte)i;
    
                    String s="12";
                    int k=Integer.parseInt(s);
    
                    //In terms of Inheritence we use Upcasting and Downcasting word.
                    //when child get own object from parent class that is called Downcasting
                    Dog dog=(Dog)animal;
            

ii. Widening

  • Widening means when you convert a small data type into large data type.
  • When you follow this direction that is called Widening.
    byte -> short -> int -> long -> loat -> double
  • It is also called Implicit conversion.
  • It is also called Upcasting.
  • Example
                    //this type of conversion is called Implicit or Widening.
                    byte i=10;
                    int b=i;
    
                    //when parent hold object of own child class that is called Upcasting.
                    Animal animal=new Dog();
            

There are some rules which supported by default in Java:

byte + byte = int

byte + anynumber = int

byte + short = int

short + short = int

char + char = int

int + int = int

int + long = long

long + float = float

float + double = double

String + anything = String

No comments: