问题描述
byte a = 1;
byte b = 1;
byte c = a + b;
抛出错误:可能损失精度
Throws error: possible loss of precision
byte subt = a_s - a_b;
^
required: byte
found: int
这种行为是否与 jvm 有关或它是用 java 语言定义的.
Is this behavior has something to do with jvm or its been defined in java language .
如果它是用 java 语言定义的,那么是因为要记住 jvm 吗?
EDIT : And if it is defined in java language then does it because of keeping jvm in mind ?
意味着,如果Java支持的字节代码>数据类型,那么为什么<代码>上字节操作代码>结果<代码> INT 代码>
Means if java supports byte
datatype then why operation on byte
results int
推荐答案
如果java支持字节数据类型,那么为什么对字节的操作结果是int
if java supports byte datatype then why operation on byte results int
因为 Java 虚拟机就是这样设计的.没有指令集可以对字节类型执行操作.而是 int
类型的指令集用于 boolean
、byte
、char
和 的操作>短
类型.
Because that's how the Java Virtual Machine is designed. There is no instruction set to perform operation on a byte type. Rather the instruction set for int
type is used for the operation on boolean
, byte
, char
, and short
types.
来自 JVM 规范 - 第 2.11.1 节:
编译器使用 Java 虚拟机指令对 byte
和 short
类型的大量文字值进行编码,这些指令将这些值符号扩展为 int类型的值code> 在编译时或运行时.
boolean
和 char
类型的文字值的加载使用在编译时将文字零扩展为 int
类型的值的指令进行编码或运行时.[..].因此,大多数对实际类型 boolean
、byte
、char
和 short
的值的操作都是由指令正确执行的对计算类型 int
的值进行操作.
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
.
该部分也说明了这背后的原因:
The reason behind this is also specified in that section:
由于Java虚拟机的一个字节的操作码大小,编码类型为操作码的地方在它的指令集的设计压力.如果每个输入指令支持的所有Java虚拟机的运行时间数据类型的,会有更多的指令比可以在<代码>字节代码>来表示.[...] 可以根据需要使用单独的指令在不受支持和支持的数据类型之间进行转换.
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.
有关所有指令集可用于各种类型的详细信息,您可以浏览该部分中的表格.
For the details on what all instruction sets are available for various types, you can go through the table in that section.
还有一个表指定实际类型到JVM计算类型的映射:
There is also a table specifying the mapping of actual type to the JVM computational type:
这篇关于由于java语言规则或jvm,添加字节转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!