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类型的操作.
A compiler encodes loads of literal values of types
byte
andshort
using Java Virtual Machine instructions that sign-extend those values to values of typeint
at compile-time or run-time. Loads of literal values of typesboolean
andchar
are encoded using instructions that zero-extend the literal to a value of typeint
at compile-time or run-time. [..]. Thus, most operations on values of actual typesboolean
,byte
,char
, andshort
are correctly performed by instructions operating on values of computational typeint
.
其背后的原因也在该部分中指定:
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计算类型的映射: