7
int a = 1L; 

This doesn't compile (of course). incompatible types: possible lossy conversion from long to int

int b = 0; b += Long.MAX_VALUE; 

This does compile!

But why is it allowed?

0

2 Answers 2

10

When you do += that's a compound statement and Compiler internally casts it. Where as in first case the compiler straight way shouted at you since it is a direct statement :)

The line

b += Long.MAX_VALUE; 

Compiler version of it equivalent of

b += (int)Long.MAX_VALUE; 

of course there will be lossy conversion from conversion of long to int.

http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#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.

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

1 Comment

ah i c, didn't found it in the spec myself. Well a warning of the compiler/IDE would be nice.
2

Actually the compiler is smarter than you think. At compile time itself, it will replace the actual value of the expression b+=Long.MAX_VALUE by -1. So, Long.MAX_VALUE is converted to an int and assigned to the int field at compile time itself)

Byte code :

public static void main(java.lang.String[]); descriptor: ([Ljava/lang/String;)V flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=2, args_size=1 0: iconst_0 1: istore_1 2: iinc 1, -1 // Here 5: return LineNumberTable: line 4: 0 line 5: 2 line 6: 5 LocalVariableTable: Start Length Slot Name Signature 0 6 0 args [Ljava/lang/String; 2 4 1 b I 

1 Comment

hm currently i am thinking the compiler is too "smart" here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.