wellnwill Marathahalli Bangalore

Type Casting


Types of Programming Languages

Assigning a value of one type to a variable of another type is known as Type Casting.

Ex- byte b1=10;
    int i = b1 ; // here we are assigning byte type value to integer type variable.

Types of Casting

There are two types of type casting in java.

  • Implicit casting
  • Explicit casting

Implicit casting (widening): Automatic type conversion

This type of type casting will be performed by java complier implicitly.

In implicit type casting, compiler will convert smaller data type value to higher data type variable so the conversion will be safe. This process is also known as safe conversion or up casting.

Ex- float f1=10; System.out.println(f1); //10.0

Note : here compiler is converting integer type value to float type automatically.

Explicit casting (Narrowing):

When we assign higher type value to lower type variable then we need to perform explicit type casting. This process is also known as unsafe conversion or down casting.

Ex- int i = 10;
    byte b1 = (byte)i ; // here we are responsible to convert integer type value to byte type variable explicitly.

Examples :

class Test149{
  public static void main(String[] args)
  {
       char ch='a';
	   int i=ch; //implicit conversion
       System.out.println(i);	
  }
}

//O/P -  97
class Test150{
   public static void main(String[] args)
   {    
       byte b1=65;
       char ch=(char)b1;
       System.out.println(ch);	
   }
}

//O/P -  A
class Test151{
  public static void main(String[] args)
  {    
      double d1=65.65;
       short sh1=(short)d1;
      System.out.println(sh1);	
  }
}

// O/P -  65
class Test152{
  public static void main(String[] args)
  { 
                int i=257;
	  byte b1=(byte)i;
      System.out.println(b1);	
  }
}

// O/P -  1

Explanation of program Test 152 :

More Examples :

class Test153{
   public static void main(String[] args)
    {
	   String s1=(String)257;
       System.out.println(s1);	
    }
}

//O/P - CompileTimeError - 
        int can not converted into String
class Test154{
   public static void main(String[] args)
   {
       float f1=10;
       System.out.println(f1);	// 10.0  
   }
}

//O/P - 10.0

class Test0155{
  public static void main(String[] args)
  {
       char ch='a'++;//invalid
	   int i=ch; //implicit conversion
       System.out.println(i);	
  }
}

//O/P -  required variable, found value
Footer with Map