Tuesday, 15 May 2018

java - Why does the compiler not give an error for this addition operation?




I know that the compiler does implicit type conversion for integer literals.
For example:




byte b = 2; // implicit type conversion, same as byte b = (byte)2;


The compiler gives me an error if the range overflows:



byte b = 150; // error, it says cannot convert from int to byte


The compiler gives the same error when the variable is passed an expression:




byte a = 3;
byte b = 5;
byte c = 2 + 7; // compiles fine
byte d = 1 + b; // error, it says cannot convert from int to byte
byte e = a + b; // error, it says cannot convert from int to byte


I came to the conclusion that the result of an expression that involves variables cannot be guaranteed. The resulting value can be within or outside the byte range so compiler throws off an error.




What puzzles me is that the compiler does not throw an error when I put it like this:



byte a = 127;
byte b = 5;
byte z = (a+=b); // no error, why ?


Why does it not give me an error?


Answer



The answer is provided by JLS 15.26.2:





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);




So, as you can see, the latest case actually work because the addition assignment (as any other operator assignment) performs an implicit cast to the left hand type (and in your case a is a byte). Extending, it is equivalent to byte e = (byte)(a + b);, which will compile happily.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...