Float to byte and back in switch
Ella Ananeva
ella.ananeva at oracle.com
Thu Oct 19 17:01:35 UTC 2023
Hi team,
When we match labels in switch with primitive types, the spec defines the behavior for integral types and for floating-point types.
• If T is a primitive type, then a case label with a case constant c applies to a value that is of type char, byte, short, int, long, float, double, boolean, String or an enum type if the constant c is equal to the value.
Equality is defined in terms of the == operator (15.21<https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.21>) for the integral types and the boolean type, and in terms of representation equivalence (java.lang.Double<https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Double.html#repEquivalence>) for the floating-point types. If the value is a String, equality is defined in terms of the equals method of class String.
What should be the behavior, though, when we try to match an integral type to a floating-point type?
e.g., In this scenario:
private static void testSwitch(float y) {
System.out.println(y == 1); //prints true
switch (y) {
case 1 -> { System.out.println(y == 1);}//throws a compile-time error: constant label of type int is not compatible with switch selector type float
default -> { }
}
}
I would expect the compiler to be able to handle this situation: since int can be converted to float and the equality operator returns true, the label should be chosen.
The opposite situation with narrowing conversion, when we try to convert float to int may be trickier, but shouldn’t it also be accepted?
Thank you,
Ella Ananeva
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231019/9ba29ac0/attachment.htm>
More information about the amber-dev
mailing list