标签:ted href turn virt rod des als was remove
对于char,short和byte这些类型在计算时都会提升到int型来计算,所以a+b=3(这个3是int型的,所以我们需要将它强转成为byte类型,才不会出错。但是使用 += 或者 ++ 运算符可以执行隐式类型转换。
//精度高的转化为低的这叫向下转。
public class PlusEquals {
public static void main(String[] args) {
byte a = 1;
byte b = 2;
a = a + b;
System.out.println(a);
}
}
What does this program print?
Did you guess 3? Too bad, this program won‘t compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int
. This, I believe was because the Java Virtual Machine doesn‘t define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b
doesn‘t work, that would mean a += b
would never work for bytes if it E1 += E2
was defined to be E1 = E1 + E2
. As the previous example shows, that would be indeed the case. As a hack to make +=
operator work for bytes and shorts, there is an implicit cast involved. It‘s not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn‘t be removed.
标签:ted href turn virt rod des als was remove
原文地址:https://www.cnblogs.com/cold-windy/p/11518361.html