I can't think of a proper subject for this one

Hi fellow Java-know-it-alls,

I have known this for years, but whats the reasoning behind this one:


      int a = 5;
      a *= 0.5f; // all fine ?!
      a = a * 0.5f; // compiler error

I know the 2nd line makes an implicit cast in bytecode, but still…

a = a * 0.5f; // compiler error

The right-hand side is converted to floating point because of 0.5f and then multiplied to a. So to assign the floating point value on the right-hand side to the left-hand side, you need to do a conversion:

a = (int)(a * 0.5f); // ok

Eh… ofcourse, I know that

But why is the 2nd line correct…

Implied cast with:

“operator=”

Here’s something else:
float a = 1/3;
print(a), will give you 0.
Why?

1/3 cannot be represented as an integer.

well, I mentioned the implicit cast in my opening-post.

But why would “operator=” have an implicit cast, what makes it so different from the “var = var operator var”…

The employees at Sun were all drunk when it happened?

because thats an integer division >.>, you need float a = 1/3f or similar.

as the original question, i have wondered that myself.

I believe for the 2nd line, all calculations are done as int. 0.5f is converted to int before it is multiplied with a!?

If I am correct then:

int a = 5;
a = (int)(a * 0.5f);
-> a becomes 2

int a = 5;
a *= 0.5f;
-> a becomes 0

Anybody willing to test it out?

Apparently you are wrong, a = 2.

Alright ;D Was just a guess …

The two expressions are not equivalent. The JLS says about the first one:

15.25.2 Compound Assignment Operators
All compound assignment operators require both operands to be of primitive type, 
except for +=, which allows the right-hand operand to be of any type if the left- hand operand is of type String.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), 
where T is the type of E1, except that E1 is evaluated only once. Note that the implied cast to type T 
may be either an identity conversion (§5.1.1) or a narrowing primitive conversion (§5.1.3). 
For example, the following code is correct:


short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:


short x = 3;
x = (short)(x + 4.6);

5 * 1/2 = 2.5, but because the storage is an integer = 2.