Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

assign int to byte vs double to float in java

1.when we assign double to float variable compiler gives us error

float f = 2753.2211;

possible loss of precision Required to cast.

2.when we assign int to byte variable compiler don't gives us error

byte b = 24;

OK

In second case data can also be lost.Then why casting explicitly is not necessary.?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The second case is explicitly allowed by the JLS as a special case. In JLS 5.2, which deals with narrowing conversions, it says:

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

...

In other words, for the non-long integer-like values, you can implicitly narrow them iff the value you're narrowing is a constant that fits within the type you're specifying.

I'm guessing the same trick isn't applied to floats because floating point values are trickier than integer values. For instance, 0.1 can't be exactly expressed in a floating point, while 1.0 can. That means that double d = 0.1 isn't actually putting the value 0.1 into d -- just a value that's very close to 0.1. Given that, the "does it fit exactly" rule doesn't apply even to floating point literals, and the question of "does it fit exactly when we narrow" becomes trickier. Your options would basically be:

  • always allow it (which could cause some surprising behavior if a value is significantly different than its literal representation)
  • only allow it if the value can be exactly put in. This would look highly inconsistent:
    • float f1 = 1.0 and double d1 = 1.0 both work
    • double d2 = 0.1 works, but float f2 = 0.1 doesn't -- confusing!
  • never allow it (slightly inconvenient, because you have to type the f char in the literal)

Given these options, it seems that the designers of the JLS chose the least of three not-great options.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...