Why * = does not give any errors when implicitly starting float in int?

I came across a situation before when I tried the following two bits of code:

int score = 100; score = score * 1.05; 

and

 int score = 100; score *= 1.05; 

The first crash (and obviously so, I'm trying to implicitly use float for int). But the second worked perfectly. The compiler did not complain, and I did not receive errors at runtime. Why does the second work and the first not? As far as I know, x *= y is just a shorthand for x = x * y .

+7
java casting compilation compiler-errors
source share
3 answers

Auxiliary assignment operators behave somewhat differently than their "extended" version. JLS Quoting , section 15.26.2 :

The compound assignment expression E1 op = E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type E1, except that E1 is evaluated only once.

It implicitly returns to the type of the variable on the left side, so there is no error casting a float into int ; it is already implicitly discarded to int .

This does not happen with the = operator, which is defined by JLS, section 5.2, Assignment Conversion :

Destination contexts allow you to use one of the following values:

  • identity transformation (§5.1.1)

  • expanding primitive conversion (§5.1.2)

  • expanding reference conversion (§5.1.5)

  • box conversion (§5.1.7) optionally followed by extension of the link conversion

  • the unboxing transform (§5.1.8), optionally followed by an extension of the primitive transform.

The following talks about a possible narrowing transformation, but only for constant expressions, and only for constant expressions: byte , char , short or int , none of which are applicable here.

+4
source share

First

 int score = 100; score = score * 1.05; 

basically says:

 int score = 100; score = (float)(score * 1.05); 

This is because if you break a float with an integer, you get a float. It cannot be assigned to an integer.

but

 int score = 100; score *= 1.05; 

Basically means

 int score = 100; score = (int)(score * 1.05); 

This is because you are not assigning a float, the calculation is done, and the assignment is first converted to int.

Here's how it makes sense to me. Hope this helps.

+3
source share

if you use:

 int score=100; score *=1.05; 

This is equivalent to:

 score=(int)(score*1.05); 

It is explained in more detail here: http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.26.2

The compound assignment expression E1 op = E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type E1, except that E1 is evaluated only once.

0
source share

All Articles