Working with Expression in Java

As you might have figured it out, today I am going to share some code playing with expressions, simple arithmetic, conversion and typecasting.

Compound statement, typecasting and assignment.

x+=i; is not equal to x=x+i;

Many programmers might think that above two statement are identical, talk is cheap let me show you the code...



public static void main(String args[])

{

short x=0;

int i=123456;

System.out.println(x+=i);

System.out.println(x=x+i);

}



Here we thought the first println will print output 123456, but thats not true, after the execution it shows -7616, the int i is too big to fit in short x, the automatically generated cast lops off the two higher-order bytes of the int value, because the JLS says...

x+=i; means x=(type of x)(x+i);

Here the statement gets automatically typecasted to operand x. In other words "compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side."


But the same cannot be applied to x=x+i; this is an illigle attempt to assign an int value to a short variable which requires and explicit cast, it cannot perform narrowing cast implicitly

x=x+i;//type mismatch cannot convert from short to int

Lets flip this, we will make the first statement illegal and the second legal by changing the code as below.


Now we're gonna revert the case.
This time we will code in a way that first println will be illegal and the second will be legal, here's how it looks like.

public static void main(String args[])
{
Object x="Hello";
String i="World";
System.out.println(x+=i);
System.out.println(x=x+i);
}

No surprise you read it right, the simple assignment is legal because x+i is of type String, and String is assigment compatible with Object class.

But why its not working with the compound statement i.e. the second println statement, because the compound assignment operators require both operands to be primitives, there is one exception to this : the += operator allows its right-hand operand to be of any type if the variable on the left-hand is of type String, in which case the operator performs string concatenation, but we have an Object type on the left hand side, so this wont apply here.




Comments

Popular posts from this blog

Integer.MAX_VALUE, Double.POSITIVE_INFINITY and Double.NaN in Java