ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

由于java语言规则或jvm,是否将字节转换为int?

2019-09-17 03:02:15  阅读:205  来源: 互联网

标签: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类型的操作.

JVM Spec – Section 2.11.1开始:

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.

其背后的原因也在该部分中指定:

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. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有