Java: byte to int math sum conversion. Identical operation results in both allowed and disallowed action

Viewed 70

This is about a sum of two ints after a cast to bytes in both operands. I'm just trying to understand why the following output works perfectly in Java:

byte b1 = (byte)128 + (byte)18;   // ok
System.out.println( b1 );   

and the latter fails at compile-time:

byte b2 = (byte)110 + (byte)18;  // compile-time error
System.out.println( b2 );  

They are identical, except from the int values used as operands. In both cases the result is out of range, but only the second snippet will throw compile-time error (altought its result is less than the the previous one). Just why is this happening?

3 Answers

Since you are using constants the compiler can check the actual value produced by the expressions.

In your first expression (byte)128 equals -128 which added to 18 produces a valid byte, which you are then assigning to a byte variable, which is valid.

However in your second expression the result of (byte)110 + (byte)18 is outside the range of bytes and thus converted to an int which you are then assigning to a byte, which is invalid. To get the second expression to work you should change it to byte b1 = (byte)((byte)110 + (byte)18)

(byte)128 equals to -128 so in the first example you will add 18 to -128. you can add additional cast to byte, please see the following examples:

byte b2 = (byte) ((byte)110 + (byte)18);  
System.out.println( b2 );

Or

byte b2 = (byte) (110 + 18);  
System.out.println( b2 );

As Vikash Madhow mentions, its to do with the type of data you are using. This link helped me: https://www.w3schools.com/java/java_data_types.asp#:~:text=There%20are%20eight%20primitive%20data%20types%20in%20Java%3A,numbers%20from%20...%20%204%20more%20rows%20

You should use casting sparingly, it's a way of you overriding the computer and saying you know best which is very open to breaking the code. If you were using variables instead of hardcoded values, you could very easily see values in there which could break this code regularly.

Related