Friday, September 2, 2011

Casting in Java

Arithmetic Promotion

Arithmetic promotion happens when narrower types need to be promoted to wider types in order to make sense in an operation among other wider types.

Basic rules for binary operators and most of the unary operators:

* All arithmetic expressions are promoted to the wider of the operands.
* The promotion is at least to int, even if no int operand appears.

These rules don't apply to the unary operators: ++ and -- and assignment operators.

Example #1:

byte x = 1;

x++; // Ok. x is now equal to 2.

x = x + 1; // Error. Expression x + 1 is promoted to int.

Example #2:

byte a = 1;

byte x = 23;

x <<= a; // Ok. x is now equal to 46.

x = x << a; // Error. Expression x << a is promoted to int.

Example #3:

char a = 5;

short x = 3;

x *= a; // Ok. x is now equal to 15.

x = x * a; // Error. Expression x = x * a is promoted to int.

Example #4:

byte a = 15;

a = -a; // Error. -a is promoted to int.

a = ~a; // Error. ~a is promoted to int.

Example #5:

float a = 1.0f;

int b = 15;

int x = a * b; // Error. Expression is promoted to float.

int x = (int)(a*b); // Ok. We cast the float result back to int. 

Primitives and Casting

Casting means explicitly telling Java to make a conversion. A casting operation may widen or narrow its argument. To cast a value, you need to precede it with the name of the desired type enclosed within parentheses:

byte x = 15;

int r = (int)(x * 3);

Booleans cannot be casted. Don't bother with them, stuff like this doesn't work:

byte a = 1;

boolean status = a;

Narrowing runs the risk of loosing information, in fact, many times you know that you are going to loose information and it is important to know which part information is going to be loosen and naturally, what information will be kept.

No comments:

Post a Comment