Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"+=" operator and int long usage [duplicate]

Tags:

java

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?

like image 736
coder Avatar asked Sep 21 '15 12:09

coder


2 Answers

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.

like image 52
Suresh Atta Avatar answered Oct 14 '22 00:10

Suresh Atta


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
like image 22
TheLostMind Avatar answered Oct 14 '22 00:10

TheLostMind