問題描述
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?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!