由于java语言规则或jvm,是否将字节转换为int?

byte a = 1;
byte b = 1;
byte c = a + b;

引发错误:可能会损失精度

byte subt = a_s - a_b;
                ^
  required: byte
  found:    int

这种行为是与jvm有关还是在java语言中定义的.

编辑:如果它是用java语言定义然后这样做,因为记住jvm?

意味着如果java支持byte数据类型,那么为什么对byte的操作会产生int

解决方法:

if java supports byte datatype then why operation on byte results int

因为这就是Java虚拟机的设计方式.没有指令集对字节类型执行操作.而是int类型的指令集用于对boolean,byte,char和short类型的操作.

JVM Spec – Section 2.11.1开始:

A compiler encodes loads of literal values of types byte and short using Java Virtual Machine instructions that sign-extend those values to values of type int at compile-time or run-time. Loads of literal values of types boolean and char are encoded using instructions that zero-extend the literal to a value of type int at compile-time or run-time. [..]. Thus, most operations on values of actual types boolean, byte, char, and short are correctly performed by instructions operating on values of computational type int.

其背后的原因也在该部分中指定:

Given the Java Virtual Machine’s one-byte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine’s run-time data types, there would be more instructions than could be represented in a byte. […] Separate instructions can be used to convert between unsupported and supported data types as necessary.

有关所有指令集可用于各种类型的详细信息,您可以查看该部分中的表.

还有一个表指定实际类型到JVM计算类型的映射:

上一篇:软件工程基础第二次作业


下一篇:WEB综合案例-黑马面面案例介绍与熟悉业务模块