tertiary operator error casting Float to Object
Remi Forax
forax at univ-mlv.fr
Fri Sep 15 23:48:59 UTC 2023
> From: "Liangtao" <gliangtao at gmail.com>
> To: "compiler-dev" <compiler-dev at openjdk.org>
> Sent: Saturday, September 16, 2023 1:23:15 AM
> Subject: Re: tertiary operator error casting Float to Object
> Sorry for the typo (now fixed)
> On Fri, Sep 15, 2023 at 4:21 PM Liangtao < [ mailto:gliangtao at gmail.com |
> gliangtao at gmail.com ] > wrote:
>> The following code always output incorrect casting result:
>> // BEGIN Bug.java code
>> public class Bug {
>> public static void main(String[] args) {
>> float temp = 60.0f;
>> boolean isInt = true;
>> Object o = isInt ? Integer.valueOf((int)temp) : Float.valueOf(temp);
>> System.out.println("isInt " + isInt + ", temp = " + o);
>> }
>> }
>> // END Bug.java code
>> Steps to reproduce:
>> $ javac Bug.java && java Bug
>> Actual Result:
>> isInt true, temp = 60.0
>> Expected Result:
>> isInt true, temp = 60
This is a well known oddities of the Java spec, the result of ?: with an Integer and a Float is a float,
inside a ?: the wrappers behave like their primitive counterparts,
see [ https://docs.oracle.com/javase/specs/jls/se20/html/jls-15.html#jls-15.25 | https://docs.oracle.com/javase/specs/jls/se20/html/jls-15.html#jls-15.25 ]
So your code is equivalent to:
float o = isInt ? Integer.valueOf((int)temp) : Float.valueOf(temp);
If you want the wrappers to behave like objects inside a ?:, you have to cast one them as an Object.
Object o = isInt ? (Object) Integer.valueOf((int)temp) : Float.valueOf(temp);
regards,
Rémi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20230916/e74f86d0/attachment-0001.htm>
More information about the compiler-dev
mailing list