0

This is wrong:

byte i = 2;
byte j = 3;
i = i + j;  

Solution Manually:

byte i = 2;
byte j = 3;
i = (byte) (i + j);      

Shortcut Solution:

byte i = 2;
byte j = 3;
i += j;

What bugs me is why is necessary to cast when we are adding the same data types (byte + byte) and respecting their MAX and MIN value of total storage.

If a byte has a range of MAX and MIN of storage integers from -128 to 127, and 2 + 3 = 5 so

why is it necessary in the example above to cast if they satisfy the range and they both are the same data type?

I also investigated and compound operators by default they cast behind the scenes, but why all this hassle regarding the process of java has behind the scenes to cast like this even in my examples?

Personally not make sense to have inherent this on Java, somebody can explain to me in depth why it is built-in in this way?

  • Discussed for C# here https://stackoverflow.com/a/941665/73226. And for Java... https://stackoverflow.com/q/18483470/73226 – Martin Smith Apr 14 '20 at 20:13
  • 2
    This is also explained in the JLS under [§4.2.2 Integer Operations](https://docs.oracle.com/javase/specs/jls/se14/html/jls-4.html#jls-4.2.2): "*If either operand is not an int, it is first widened to type int by numeric promotion.*" – Vince Apr 14 '20 at 20:20
  • "solution manually" surely that is also broken, it would need to be `(byte) (i + j)`? – Andy Turner Apr 14 '20 at 20:22
  • 1
    Does this answer your question? [Is addition of byte converts to int because of java language rules or because of jvm?](https://stackoverflow.com/questions/18483470/is-addition-of-byte-converts-to-int-because-of-java-language-rules-or-because-of) – Savior Apr 14 '20 at 20:37
  • Related: [Why don't Java's +=, -=, *=, /= compound assignment operators require casting?](https://stackoverflow.com/questions/8710619/why-dont-javas-compound-assignment-operators-require-casting). – Mark Rotteveel Apr 16 '20 at 16:01

0 Answers0