java - 为什么在评估表达式时将 byte 和 short 值提升为 int

标签 java type-promotion

<分区>

我想知道为什么每当对表达式求值或按位计算时,byteshort 值都被提升为 int 的原因操作已处理?

最佳答案

因为 Java 语言规范是这么说的。 Section 5.6.1为某些运算符的评估定义一元数字提升,它说:

  • If the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

Section 5.6.2关于二进制数字运算符的评估(“二进制”表示具有两个操作数的运算符,如“+”)说了类似的话:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

为什么这样定义?一个主要原因是在设计 Java 语言和 Java 虚拟机时,32 位是计算机的标准字长,用较小的类型进行基本运算没有性能优势。 Java 虚拟机旨在利用这一点,通过使用 32 位作为 int 大小,然后在 the Java bytecode 中提供专用指令。适用于整数、长整数、 float 和 double 的算术运算,但不适用于任何较小的数字类型(字节、短整型和字符)。消除较小的类型使字节码更简单,并让完整的指令集(有 future 扩展的空间)仍然适合单个字节的操作码。类似地,JVM 的设计偏向于在 32 位系统上轻松实现,在类和堆栈中的数据布局中,其中 64 位类型( double 和长整型)占用两个插槽,而所有其他类型(32-位或更小)占用一个插槽。

因此,较小的类型在 Java 的设计中通常被视为二等公民,在不同的步骤中转换为 int,因为这简化了一些事情。较小的类型仍然很重要,因为它们打包在一起时占用的内存较少(例如,在数组中),但它们在计算表达式时没有帮助。

关于java - 为什么在评估表达式时将 byte 和 short 值提升为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27582233/

相关文章:

java - 我们如何从 JBoss 目录中自动删除standalone\tmp\vfs\temp

java - 尝试将api中的数据获取到JSON时在JSONArray上使用NullPointer

java - 如何使用Primefaces在Java中查找数据源(dataTable)?

java - java中的提升和转换

c - 乘以混合数据类型时,float 是否总是自动转换为 double?

java - Long 的大小为 8 字节,那么在 JAVA 中如何将 'promoted' 转换为 float (4 字节)?

java - 为什么模拟 mongotemplate.aggregate() 返回 NullPointerException [Spring Boot Mockito]

java - 字节加法转换为int是因为java语言规则还是因为jvm?

java - 如何在不使用新的 java.util.concurrent 包的情况下在 Java 中处理数千个线程