由于java语言规则或jvm,添加字节转换为int?

时间:2023-04-06
本文介绍了由于java语言规则或jvm,添加字节转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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 类型的指令集用于 booleanbytechar 的操作>短类型.

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 虚拟机指令对 byteshort 类型的大量文字值进行编码,这些指令将这些值符号扩展为 int 在编译时或运行时.booleanchar 类型的文字值的加载使用在编译时将文字零扩展为 int 类型的值的指令进行编码或运行时.[..].因此,大多数对实际类型 booleanbytecharshort 的值的操作都是由指令正确执行的对计算类型 int 的值进行操作.

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.

该部分也说明了这背后的原因:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!