What happened to my code? The following code worked for integer type of data, but couldn't work for byte type of data.
public class Exchange {
public static void main(String[] args) {
//int a = 23, b = 44;
byte a = 23, b = 44;
a = a + b;
b = a - b;
a = a - b;
System.out.println("a=" + a + "b=" + b);
}
}
I know that the data-type byte can hold data of the range -2^(8-1) to -1+2^(8-1). But I'm using 23 & 44, so it's less than 127.
Here I got error message "incompatible types: possible lossy conversion from int to byte".
a=127andb=127would the result fit in onebyte?a += b; b = (byte) (a-b); a -= b;-- compound assignments (like+=) automatically do the casting -- the second calculation can be replaced byb -= a; b *= -1;orb += a-2*b;to make it even more unclear, I mean, make it not using casts -- I would still prefer using a temporary variable, instead of a bunch of operations just to save one stack position