Friday 31 August 2012

Type conversion


Type Casting  refers to changing an entity of one datatype into another. This is important for the type conversion in developing any application. If you will store a int value into a byte variable directly, this will be illegal operation. For storing your calculated int value in a byte variable you will have to change the type of resultant data which has to be stored.
Automatic Conversion
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double

lets take an example,
// 64 bit long integer

long myLongValue;

// 32 bit standard integer 

int myIntValue;

myLongValue = myIntValue;

Java follows two types of casting

  • Upcasting
  •  Downcasting

Upcasting
Casting a reference with the class hierarchy in a direction from the sub classes towards the root then this type of casting is termed as upcasting. Upcasting does not require a cast operator.
DownCasting
On the other hand, casting a reference with hierarchal class order in a direction from the root class towards the children or subclasses, then it is known as downcasting.
Here we discussing one example,where we converting int value to byte.

int x=10;
byte b =(byte) x;

here first we assign the int x to 10;Then we try to convert int x to byte and try to store in the variable byte b.for that we using byte b =(byte) x;

Explicit Conversion (Casting)

Automatic type casting does work in case of narrowing i.e. when a data type requiring more storage is converted into a data type that requires less storage. E.g. conversion of a long to an int does not perform because the first requires more storage than the second and consequently information may be lost. In such situations an explicit conversion is required. 

No comments:

Post a Comment