6

Assign int to byte vs double to float in java

 3 years ago
source link: https://www.codesd.com/item/assign-int-to-byte-vs-double-to-float-in-java.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Assign int to byte vs double to float in java

advertisements

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


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.

Tags java

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK