Wednesday, 25 December 2013

Conversion of data types


A data type of lower size (occupying less memory) is assigned to a data type of higher size.
int x = 10; // x occupies 4 bytes
double y = x; // y occupies 8 bytes

A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size.requires explicit casting; a casting operation to be performed by the programmer. The higher size is narrowed to lower size. Eg:
 double x = 10.5; // 8 bytes
int y = x; // 4 bytes ; raises compilation error
we need to explicitly convert it
 double x = 10.5;
 int y = (int) x;
The double x is explicitly converted to int y. The thumb rule is, on both sides, the same data type should exist.
A boolean value cannot be assigned to any other data type. Except boolean, all the remaining 7 data types can be assigned to one another either implicitly or explicitly; but boolean cannot. We say, boolean is incompatible for conversion. Maximum we can assign a boolean value to another boolean.
Following raises error.
       boolean x = true;
       int y = x;                    // error
       boolean x = true;
       int y = (int) x;           // error
byte –> short –> int –> long –> float –> double
In the above statement, left to right can be assigned implicitly and right to left requires explicit casting. That is, byte can be assigned to short implicitly but short to byte requires explicit casting.
int to char requires explicit casting.
byte to char and char to byte requires expilcit casting.
char to short or short to char requires explicit casting.
float to char requires explicit casting.

No comments:

Post a Comment