byte type operation details

As we all know, the integer data type in Java is the default type int, byte when we use the time to be careful, because if the two variables of type byte result of the addition is assigned to a variable of type byte will compile errors . Consider the following code:

Here reported a compile error: Type mismatch: can not convert from int to byte. Why would report such a mistake? Obviously I b1, b2 are byte type of data, b1, b2 added value does not exceed the byte can represent maximum range, what is it the cause of the error. Next, as you explain why. b1, b2 two byte data is good, but at the same time b1, b2 also two variables , the values of two variables together after how much (that is likely to exceed the byte can represent maximum range), but we must not known, of course, it is not known java, so java will b1, b2 addition result is automatically promoted to the int type, the default data type is an integer of java, so in this case will be reported in such a compile error. 
 

Look at the following code: 

At this point, there is no code compilation errors. Because the right side of an assignment statement is two constants, we know their maximum range and does not exceed the byte can be represented, of course, also know java, so it will not report compilation errors.  Above it can be verified by the following FIG.

  • Since the largest integer that can be represented is 127, 127 byte + 3 byte clearly exceeds the maximum range that can be represented by the compiling errors: Type Mismatch: from int can not be converted to byte . Conclusion: When an integer value to represent the range of automatically converted int int, even if the original is a byte . 
byte i = ‘B’;
Output i, will output 66.
 

 

Guess you like

Origin www.cnblogs.com/wzdnwyyu/p/11095627.html