gpt4 book ai didi

java - 为什么变量的大小不随我们使用的 JVM 平台(64 位或 32 位)而改变?

转载 作者:行者123 更新时间:2023-12-01 07:05:51 25 4
gpt4 key购买 nike

我遇到了一个问题:我们声明的所有变量(int、float、char double)都具有相同的内存大小,即使 JVM 平台不同(32 位或 64 位)int占4个字节 float 4 字节字符 2 字节这是什么原因??

最佳答案

在 Java 中,Java 虚拟机规范明确指出这些类型就是这些大小。请参阅2.3. Primitive Types and Values :

The integral types are:

  • byte, whose values are 8-bit signed two's-complement integers, and whose default value is zero
  • short, whose values are 16-bit signed two's-complement integers, and whose default value is zero
  • int, whose values are 32-bit signed two's-complement integers, and whose default value is zero
  • long, whose values are 64-bit signed two's-complement integers, and whose default value is zero
  • char, whose values are 16-bit unsigned integers representing Unicode code points in the Basic Multilingual Plane, encoded with UTF-16, and whose default value is the null code point ('\u0000')

The floating-point types are:

  • float, whose values are elements of the float value set or, where supported, the float-extended-exponent value set, and whose default value is positive zero
  • double, whose values are elements of the double value set or, where supported, the double-extended-exponent value set, and whose default value is positive zero

The values of the boolean type encode the truth values true and false, and the default value is false.

确实如此,某些语言的平台相关大小确实很烦人,这使得推理和使用它变得困难。 Java虚拟机是一个抽象机器,其工作方式同样独立于底层物理硬件。因此,尺寸由规范确定。这简化了独立于平台的软件的开发,这也是 Sun 最初将 Java 营销为 "write once, run anywhere" 的原因之一。 .

关于java - 为什么变量的大小不随我们使用的 JVM 平台(64 位或 32 位)而改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com