简体   繁体   中英

Java Downcasting Conversion

Why does char c = 65 work and not throw an error but float d = 65.0 not work and throws a Static Error: Bad types in assignment: from double to float? Aren't they both downcasting?

I could just quote something from the JLS section 5.2 and say "It works like this because the language spec says so", but that would not be satisfying would it?

My educated guess at why the designed the language like this:

When converting 65 to a char , what you are really doing is just stripping off a bunch of insignificant 0s in the binary representation, since char is 16 bit, whereas int is 32 bit. It's like turning 0065 to 65.

On the other hand, 65.0 is a double and is represented in a floating point format. Note that generally, this representation is only an approximation of the true value. See this post for more info. The more bits, the better the approximation. So converting from double (64 bits) to float (32 bits) is kind of like converting 0.333333 to 0.333. Hopefully you'd agree that this is a greater loss of information than turning 0065 to 65. Therefore, this is not a conversion that should be a performed automatically. Programmers need to be aware that this is happening.


Anyway, here's the relevant part of the language spec, for completeness's sake:

Assignment contexts allow the use of one of the following:

...

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.

So the language spec kind of gives byte, short, char and int special treatment, allowing them a narrowing conversion in an assignment context. Do note that the expression must be:

float d = 65.0;

65.0 is not a float value. It is a double value. When entering float values, the number must end with the letter f.

You see here.

float d = 65.0f;

If you want to give d to 65 without having to write the letter f, you can do the following.

float d = (float)65.0;

This is known as narrow casting.

65.0 in Java-sense is a double, because of the . . If you want this number to be a float, just add f behind it.

float d = 65.0f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM