Java double initialization

2020-05-21 08:48发布

In what way are these statements different?

  1. double dummy = 0;
  2. double dummy = 0.0;
  3. double dummy = 0.0d;
  4. double dummy = 0.0D;

4条回答
虎瘦雄心在
2楼-- · 2020-05-21 09:17

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.

查看更多
淡お忘
3楼-- · 2020-05-21 09:26

for Java I do not know exactly, in C this can be really dangerous if you omit this D at the end since it will not change upper bytes, which can have effect that in your variable lies number which you actually did not put in!

In Java I had a really big problem with instatntiating BigDecimal - new BigDecimal(0) and new bigDecimal(0L) is NOT the same thing, you can feel it if you migrate your code from Java 1.4 to Java 1.5. Don't know why they were sloppy about it, maybe they had to do it that way.

查看更多
可以哭但决不认输i
4楼-- · 2020-05-21 09:28

For the first one:

double dummy = 0;

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:

double dummy = 0.0;
double dummy = 0.0d;
double dummy = 0.0D;

These three are exactly the same - 0.0, 0.0d and 0.0D are just three different ways of writing a double literal. See 3.10.2 Floating-Point Literals in the JLS.

查看更多
萌系小妹纸
5楼-- · 2020-05-21 09:40

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:

double x = 100;
double y = 100.0;

compiles to:

0:  ldc2_w  #2; //double 100.0d
3:  dstore_1
4:  ldc2_w  #2; //double 100.0d
7:  dstore_3

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:

byte b = 100;

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...

查看更多
登录 后发表回答