标签:operation java byte type-conversion type-promotion
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计算类型的映射:
标签:operation,java,byte,type-conversion,type-promotion 来源: https://codeday.me/bug/20190917/1808726.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。