[英]Java Casting misunderstanding for me
I am new to java, and I don't understand the differences between these two:我是java新手,我不明白这两者之间的区别:
byte myByte = 100;
short myShort = 5000 ;
int myInt = 2_000_150_000;
long myLong = (long)(50_000 + 10*(long)(myByte + myShort + myInt));
System.out.println("test1:" + myLong);
long myLongWrong = (long)(50_000 + 10*(myByte + myShort + myInt));
System.out.println("test2:" + myLongWrong);
OUTPUT:
test1:20001601000
test2:-1473235480
I know whenever I got var and arithmetic I need to do a casting with (long) but why I need to do it outside the main () too?我知道每当我获得 var 和算术时,我都需要使用 (long) 进行强制转换,但为什么我也需要在 main () 之外进行转换?
THE SAME THINK FOR short work differently对短期工作的相同想法不同
short myShortTest = (short)(50_000 + 10*(short)(myByte + myInt +myShort));
short myShortTest2 = (short)(50_000 + 10*(myByte + myInt +myShort));
System.out.println(myShortTest);
System.out.println(myShortTest2);
OUTPUT输出
13800
13800
Your first version reads: add up my variables, treat the result as a long, multiply by 10, add 50000 and treat that as a long.您的第一个版本是:将我的变量相加,将结果视为长整数,乘以 10,再加上 50000 并将其视为长整数。
Your second version reads: add up my variables (result is an int), multiply by 10 (which is still an int but might be overflown), add 50000 (still a possibly overflown int) and treat that as a long.你的第二个版本是:把我的变量加起来(结果是一个整数),乘以 10(这仍然是一个整数,但可能会溢出),加上 50000(仍然是一个可能溢出的整数),然后把它当作一个长整数。
So your fist version starts to treat the sum as a long value and reserves sufficient memory while your second version does this step at the very end, working with lower memory until then.因此,您的第一个版本开始将总和视为一个长值并保留足够的内存,而您的第二个版本在最后执行此步骤,直到那时使用较低的内存。
Whenever an overflow happens, an int
will move to the other end of the boundary as seen in the output of the following program:每当发生溢出时,
int
将移动到边界的另一端,如以下程序的输出所示:
public class Main {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MIN_VALUE - 1);
}
}
Output:输出:
2147483647
-2147483648
-2147483648
2147483647
test1
, because of casting to long
, the result of the intermediate calculation [ 10*(long)(myByte + myShort + myInt)
] was stored as long
which can accommodate the result without an overflow and hence you got the correct value.test1
的情况下,由于转换为long
,中间计算的结果 [ 10*(long)(myByte + myShort + myInt)
] 存储为long
,可以容纳结果而不会溢出,因此您得到了正确的价值。test2
, in lack of proper cast, the result of the intermediate calculation [ 10*(myByte + myShort + myInt)
] was stored as int
but the value overflew for int
and hence you got the negative value.test2
的情况下,由于缺乏正确的转换,中间计算的结果 [ 10*(myByte + myShort + myInt)
] 被存储为int
但值10*(myByte + myShort + myInt)
了int
,因此你得到了负值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.