29

Possible Duplicate:
Java += operator

In Java, this is not valid (doesn't compile), as expected:

long lng = 0xffffffffffffL;
int i;
i = 5 + lng;    //"error: possible loss of magnitude"

But this is perfectly fine (?!)

long lng = 0xffffffffffffL;
int i = 5;
i += lng;       //compiles just fine

This is obviously a narrowing operation, that can possibly exceed the int range. So why doesn't the compiler complain?

1
  • 1
    This question invites discussion instead of a clear-cut answer. Commented Dec 19, 2012 at 10:08

3 Answers 3

14

This is defined in the JLS #15.26.2:

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.

In other words, i += lng performs a cast implicitly.

Sign up to request clarification or add additional context in comments.

11 Comments

not jelous, but i said the same darn thing in my answer a minute befor you and i got no reps.. :P
@GanGnaMStYleOverFlowErroR You just rephrased OP's question. assylias got upvoted for referencing the JLS. As opposed to you, he posted that in the first revision, and was the first one to post it; you needed about 5 revisions to get there (and only after seeing others' answers).
@GanGnaMStYleOverFlowErroR Sorry about that - but I'm certainly not going to give away the 3 hats I just got ;-)
dammit, is it all about the hats now?? :)
@MarkoTopolnik mark as said earlier, i am not greedy or something. i totally agree with you that my answer wasn't as clear as assylias or NPE, i was only making a conversation :p, and i would love to be a better cobntributor to SO .. :)
|
5

i += lng; compound assignment operator cast's implicitly.

i+=lng; 
is same as 
i = int(i+lng);

FROM JLS:

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.

2 Comments

So it seems, but why? It seems to me to go against the gist of the language.
@CristiDiaconescu, This implicit cast happens without errors because there is no syntax available to make it explicit. For example you wouldn't be able to *=1.5 an integer otherwise.
3

The compiler does not complain because, according to JLS §15.26.2. Compound Assignment Operators:

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.

Thus,

i += lng;

is equivalent to

i = (int)(i + lng);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.