Java双重初始化
这些说法有何不同?
- 双虚拟= 0;
- 双虚拟= 0.0;
- 双虚拟 = 0.0d;
- 双虚拟 = 0.0D;
In what way are these statements different?
- double dummy = 0;
- double dummy = 0.0;
- double dummy = 0.0d;
- double dummy = 0.0D;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试了一个简单的程序(同时使用 0 和 100,以显示“特殊”常量和一般常量之间的差异)后,Sun Java 6 编译器将为 1 和 2 输出相同的字节码(情况 3 和 4 与 2 相同,如下所示)就编译器而言)。
例如:
编译为:
但是,我在 Java 语言规范中看不到任何内容保证常量表达式的编译时扩展。对于以下情况,编译时会缩小:
如 第 5.2 节,但这并不完全相同。
也许比我眼睛更锐利的人可以在某个地方找到保证......
Having tried a simple program (using both 0 and 100, to show the difference between "special" constants and general ones) the Sun Java 6 compiler will output the same bytecode for both 1 and 2 (cases 3 and 4 are identical to 2 as far as the compiler is concerned).
So for example:
compiles to:
However, I can't see anything in the Java Language Specification guaranteeing this compile-time widening of constant expressions. There's compile-time narrowing for cases like:
as specified in section 5.2, but that's not quite the same thing.
Maybe someone with sharper eyes than me can find a guarantee there somewhere...
对于第一个:
整数文字
0
通过加宽基元转换转换为双精度数,请参阅 Java 语言规范中的 5.1.2 扩展基元转换。请注意,这完全由编译器完成,它对生成的字节码没有任何影响。对于其他:
这三个是完全相同的 -
0.0
、0.0d
和0.0D
只是编写的三种不同方式>双
文字。请参阅 3.10.2 浮点JLS 中的文字。For the first one:
the integer literal
0
is converted to a double with a widening primitive conversion, see 5.1.2 Widening Primitive Conversion in the Java Language Specification. Note that this is done entirely by the compiler, it doesn't have any impact on the produced bytecode.For the other ones:
These three are exactly the same -
0.0
,0.0d
and0.0D
are just three different ways of writing adouble
literal. See 3.10.2 Floating-Point Literals in the JLS.最后 3 个应该是相同的。右侧的文字已经是双精度数了。当您有十进制文字时,“d”或“D”是隐式的。
第一个略有不同,因为 0 是 int 文字,它将被扩展为 double。我不知道在这种情况下是否会产生不同的字节码;无论如何,结果应该是相同的。
The last 3 should be identical. The literal on the right side is a double already. The 'd' or 'D' is implicit when you have a decimal literal.
The first one is slightly different in that 0 is an int literal, which will be widened to a double. I don't know if that even produces different byte code in this case or not; the result should be identical anyway.