Saturday, May 18, 2013

What is type casting in Java



Automatic Type Conversion happens when two types are compatible with each other  (example int and short)  and the destination type is larger than the source type.


public class TypeCasting {
public static void main(String[] args) {

short s=5;
int i=6;
 
  i=s;
  //This is ok since int type is larger than short
  //to hold the value of short and for that nothing
  //extra is required

System.out.println("int value is " + i);
}
}


Ouput:-
int value is 5


Now consider the second scenario where we are trying to assign an int value to a short variable.


i=12;
s=i; 
//This will be a compile error since short is smaller than int
//and for that short cannot get the value of int by 
//Automatic Type Conversion. Here an explicit casting is required
//by which the int will be converted as short.

So the whole code will be


public class TypeCasting {
public static void main(String[] args) {

short s=5;
int i=6;
i=s;
System.out.println("int value is " + i);

i=12;

s=(short)i; 
  //This is type casting where int type is converted to
  //short type.

System.out.println("short value is " + s);
}
}


Ouput:-

int value is 5
short value is 12





















No comments:

Post a Comment