[英]Explicit type casting to byte overflows
public class {
public static void main(String[] args) {
// Explicit Type Conversion
long t = 70;
t= (byte) t * 2;
System.out.println("Manual conversion"+t);
}
}
Output :- Manual Conversion 140输出:- 手动转换 140
Here am getting the output 140, but why?这里得到的输出是 140,但为什么呢? Because as byte ranges from -128 to 127 so why am getting 140, as its more than 127, it's exceeding!
因为字节范围从 -128 到 127 所以为什么我得到 140,因为它超过 127,它超出了!
Let's examine the expression t=(byte)t*2
.让我们检查表达式
t=(byte)t*2
。 You have a byte
(since you explicitly cast it) multiplied by an int
(literal).你有一个
byte
(因为你显式地转换它)乘以一个int
(文字)。 The left operand is promoted to an int
in order to perform the multiplication, so 140
is a valid value there.左操作数被提升为
int
以执行乘法,因此140
是一个有效值。 It is then promoted to a long
and assigned back to t
.然后将其提升为
long
并分配回t
。
Cast has higher operator precedence than multiplication. Cast 的运算符优先级高于乘法。 Use
用
t=(byte)(t*2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.