How do compound assignment operator work for byte primitives?
The following example is from the Is 'x+=a' always equivalent to 'x=x+a'?
public class Program {
public static void main(String [] args){
byte x = 100;
System.out.println(x += 100);
}
}
output
-56
The result seems not quite expected at first. Let's see what happens step by step:
Firstly we expand the compound operator += to:
byte x = 100;
x = (byte)(x + 100);
Secondly, the addition gets evaluated: x + 100 = 200.
Then, the implicit conversion occurs: 200 int type is converted to the type of byte: 00000000 00000000 00000000 11001000 -> 11001000. Java simply truncate the higher bits that won't fit the size of the destination type.
For a byte value, the first bit is the sign. Since the first bit is 1, 110001000 is a negative number. To figure out the value of the number, just flip all the bits and then add 1 to it:
11001000 -> 00110111
00110111
+ 1
-------------
00111000
00111000 is 56. That's why the final result is -56.
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?