Type Conversion in Expressions

Type Conversion in Expressions


AUTOMATIC TYPE CONVERSION

     An expression is defined as a linear combination of operands and operators. If the operands are of different data types (int, float etc) the lower data type operand is automatically converted to the higher data type before execution. This process of conversion is called automatic type conversion. The result is of the higher type.

Example

Let,
     float b=10.7;
     int c=7;
Then b+c=17.7. here int c is converted to float.

The table given below shows the conversion.

datatype
Char
byte
short
int
long
float
double
char
short
Int
long
float
double

int
int
int
long
float
double

int
int
int
long
float
double

int
int
int
long
float
double

int
int
int
long
float
double

long
long
long
long
float
double

float
float
float
float
float
double

double
double
double
double
double
double
   
     Even though the result of the expression is converted to higher data type, the result depends on the data type of the variable on the left hand side of the expression.

Example

     int a;
     float b=10.7;
     int c=7;
     a=b+c;
The value stored in a is 17

CASTING A VALUE

     The process of converting the data type of an operand in an expression locally without affecting its data type in the declaration is called casting a value. The general form is

     (datatype)expression

Where             datatype     -     valid datatype
                       Expression -     valid expression
Example

1.       (int)(x+y)     - The result of expression a+b is converted to integer.
2.       (int)10.9       - 10.9 is converted to integer 10.
3.       (float)x+y    - x is converted to float and is added to y.

No comments:

Post a Comment

Creating Objects

Creating Objects                  Creating objects means to allocate memory space for all the instance variables of the objects. S...