对于char,short和byte类型的运算

Posted cold-windy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对于char,short和byte类型的运算相关的知识,希望对你有一定的参考价值。

对于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.

以上是关于对于char,short和byte类型的运算的主要内容,如果未能解决你的问题,请参考以下文章

java类型转换和练习

Java基本数据类型的运算

java基础再回首————数据类型和运算符

JavaSE-运算符和流程控制

JAVA核心技术I---JAVA回顾

类型转换