Type Conversion, Casting and Promotions in Java|| java language || java type casting|| java type conversion|| Java promotions..?

 Automatic Conversion:

When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:

o When two types are compatible.

Like numeric types int, float, double, byte, types are compatible with each others but these are not compatible with boolean or char.

o Destination type is larger than source type.

For example byte to int conversion, int to float conversion. These are called widening conversions.

Type Casting:

For explicit type conversions casting is used for example assigning a larger value to smaller destination this is called narrowing conversion. And for incompatible types conversion casting is used.

Syntax:

 Result = (target-type) value;

e.g. If you convert float value into int value truncation is performed and fractional part is lost. e.g. 35.043 is converted to in the result will be 35.

e.g. I you convert int into byte value. Result will be reduced modulo means int value is divided by byte 

type's range which is 256. e.g. if you assign 257 int value to byte by casting result will be 257/256 = 1.

Automatic Type Promotion in Expressions:

Consider :

byte a = 40;

byte b = 50;

byte c = 100;

int d = a * b / c;

The result of the intermediate term a * b easily exceeds the range of either of its byte operands. To handle this kind of problem, Java automatically promotes each byte or short operand to int when evaluating an expression. This means that the sub expression a * b is performed using integers—not bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are both specified as type byte.

Type Promotion Rules:

All byte and short values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double.


2 Comments

Please do not enter any spam link in the comment box

Post a Comment

Please do not enter any spam link in the comment box