Byte typecasting in java

删除回忆录丶 提交于 2019-12-02 09:11:53
Jon Skeet

The addition expression b1 + b2 is of type int - there aren't any addition operators defined on smaller types than int. So in order to convert that back to a byte, you have to cast:

byte b3 = (byte) (b1 + b2);

Note that although you happen to know that the values are small, the compiler doesn't care about the values you've set in the previous two lines - they could both be 100 for all it knows. Likewise although you know that the int you're trying to assign to a byte variable is only the result of adding two byte values together (or rather, two values promoted from byte to int), the expression as a whole is just int and could have come from anywhere as far as the language is concerned.

(The fact that the addition can overflow is a separate matter, but that would be an inconsistent argument - after all, you can add two int values together and store the result in an int variable, even though the addition could have overflowed easily.)

Because 127 is the last value of byte. Assume b1 = 127 and b2 = 2

now what happends b = b1+b2 = 129 [which is out of byte range, i.e. it's in int range]

now if you cast it b = (byte)(b1+b2), you will get -127 this is due to rounding of the value to byte.

    byte b1=3;
    byte b2=2;
    byte b3=b1+b2;  // you can't use byte here, Every time addition will result 
                     int value

Because, If you trying to cast an int which is larger than byte range, there is a loss part of that value. So addition will not allow to use byte here.

when ever you do +,-,*,/,% java internally uses a function

ex: max(int,dataType of operand 1,dataType of operand 2);

here in your code
max(int, byte,byte) ==> which one is bigger ? ==> int is bigger

so you may get POSSIBLE LOSS OF PRESSION
found :int

required : byte

Another Example

 short a =10;
 byte b=20;
 short c = a+b;

now:

internally: max(int,OP1,OP2);

ie max(int,short,byte) ==> which is bigger Data Type? int

so java excepts int

 int c = a+b;  (works fine)  

Another Example :

 long a =10;
 byte b=20;
 short c = a+b;

now:

internally: max(int,OP1,OP2);

ie max(int,long,byte) ==> which is bigger Data Type? long

so java excepts long

 long c = a+b;(works fine)  

Another Example:

byte b = 10;
b = b+1;  

now,
max(int,byte)==> which is bigger Data Type ? int
so,

int c = b+1;(works fine) or b = (byte) b+1;

hope you understand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!