Reputation: 5629
what actually happens here, when byte - byte
is occur?
suppose,
byteResult = byte1 - byte2;
where,
byte1 = 0xff;
byte2 = 0x01;
then,
is byte1
turns into integer with value 255 and and byte2
1 and byteResult
assigned to 254 then converted into byte
with 0xFE
? And then the if
condition is checked? Please a detail help will be very helpful for me. Sorry if my question is ambiguous!
Here, I found something but not what exactly I want.
Java Byte comparison
Upvotes: 0
Views: 92
Reputation: 172628
No the byte will not be converted into an int.
From the JLS 5.2 Assignment Conversion:
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int: - A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
Also check subtracting 2 bytes makes int?
This is a basic premise of Java programming. All integers are of type int unless specifically cast to another type. Therefore, any arithmetic done with integers automatically 'promotes' all the operands to int type from the narrower type (byte, short), and the result of arithmetic with int operands is always int. (I think I've beaten that to death now).
If you want the short result of arithmetic with two bytes, do this:
short result = (short) (byte1 - byte2)
This explicit cast makes it the programmer's responsibility for throwing away the extra bits if they aren't needed. Otherwise, integer arithmetic is done in 32 bits.
Upvotes: 2