Why does Java 12 try to convert the result of a switch to a number?Does a finally block always get executed in Java?How does the Java 'for each' loop work?Why can't variables be declared in a switch statement?How do I read / convert an InputStream into a String in Java?Why can't I use switch statement on a String?Why does Java have transient fields?Does Java support default parameter values?How do I convert a String to an int in Java?Why is subtracting these two times (in 1927) giving a strange result?Why does this code using random strings print “hello world”?
Strong empirical falsification of quantum mechanics based on vacuum energy density
What is Cash Advance APR?
How can Trident be so inexpensive? Will it orbit Triton or just do a (slow) flyby?
What does chmod -u do?
The screen of my macbook suddenly broken down how can I do to recover
Melting point of aspirin, contradicting sources
How can "mimic phobia" be cured or prevented?
Creepy dinosaur pc game identification
C++ debug of nlohmann json using GDB
Loading commands from file
What should you do if you miss a job interview (deliberately)?
Electoral considerations aside, what are potential benefits, for the US, of policy changes proposed by the tweet recognizing Golan annexation?
What was the exact wording from Ivanhoe of this advice on how to free yourself from slavery?
Why Shazam when there is already Superman?
Not using 's' for he/she/it
What percentage of fillings performed today are done with mercury amalgam?
height map for normal input sharp edges
How to explain what's wrong with this application of the chain rule?
What should you do when eye contact makes your subordinate uncomfortable?
Why should universal income be universal?
How much character growth crosses the line into breaking the character
Why did the EU agree to delay the Brexit deadline?
Is the U.S. Code copyrighted by the Government?
Is there a RAID 0 Equivalent for RAM?
Why does Java 12 try to convert the result of a switch to a number?
Does a finally block always get executed in Java?How does the Java 'for each' loop work?Why can't variables be declared in a switch statement?How do I read / convert an InputStream into a String in Java?Why can't I use switch statement on a String?Why does Java have transient fields?Does Java support default parameter values?How do I convert a String to an int in Java?Why is subtracting these two times (in 1927) giving a strange result?Why does this code using random strings print “hello world”?
I agree that this code:
var y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
case 3 -> true;
default -> 4;
;
System.out.println(y);
System.out.println(((Object) y).getClass().getName());
returns this:
0
java.lang.Character
But if you remove boolean:
var y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
default -> 4;
;
System.out.println(y);
System.out.println(((Object) y).getClass().getName());
returns this:
48.0
java.lang.Float
I suppose this result is unexpected.
java switch-statement java-12
add a comment |
I agree that this code:
var y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
case 3 -> true;
default -> 4;
;
System.out.println(y);
System.out.println(((Object) y).getClass().getName());
returns this:
0
java.lang.Character
But if you remove boolean:
var y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
default -> 4;
;
System.out.println(y);
System.out.println(((Object) y).getClass().getName());
returns this:
48.0
java.lang.Float
I suppose this result is unexpected.
java switch-statement java-12
Probably some kind of optimization. In the second example you can map all results to Float, in the first example they are just only Objects.
– Ralf Renz
yesterday
9
I would imagine it is for the same reason astrue ? '0' : falsewould return a Character because it necessarily requires boxing, whereastrue ? '0' : 0.0fwould return a float because binary numeric promotion would occur.
– Andy Turner
yesterday
1
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
yesterday
add a comment |
I agree that this code:
var y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
case 3 -> true;
default -> 4;
;
System.out.println(y);
System.out.println(((Object) y).getClass().getName());
returns this:
0
java.lang.Character
But if you remove boolean:
var y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
default -> 4;
;
System.out.println(y);
System.out.println(((Object) y).getClass().getName());
returns this:
48.0
java.lang.Float
I suppose this result is unexpected.
java switch-statement java-12
I agree that this code:
var y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
case 3 -> true;
default -> 4;
;
System.out.println(y);
System.out.println(((Object) y).getClass().getName());
returns this:
0
java.lang.Character
But if you remove boolean:
var y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
default -> 4;
;
System.out.println(y);
System.out.println(((Object) y).getClass().getName());
returns this:
48.0
java.lang.Float
I suppose this result is unexpected.
java switch-statement java-12
java switch-statement java-12
asked yesterday
IlyaIlya
355312
355312
Probably some kind of optimization. In the second example you can map all results to Float, in the first example they are just only Objects.
– Ralf Renz
yesterday
9
I would imagine it is for the same reason astrue ? '0' : falsewould return a Character because it necessarily requires boxing, whereastrue ? '0' : 0.0fwould return a float because binary numeric promotion would occur.
– Andy Turner
yesterday
1
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
yesterday
add a comment |
Probably some kind of optimization. In the second example you can map all results to Float, in the first example they are just only Objects.
– Ralf Renz
yesterday
9
I would imagine it is for the same reason astrue ? '0' : falsewould return a Character because it necessarily requires boxing, whereastrue ? '0' : 0.0fwould return a float because binary numeric promotion would occur.
– Andy Turner
yesterday
1
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
yesterday
Probably some kind of optimization. In the second example you can map all results to Float, in the first example they are just only Objects.
– Ralf Renz
yesterday
Probably some kind of optimization. In the second example you can map all results to Float, in the first example they are just only Objects.
– Ralf Renz
yesterday
9
9
I would imagine it is for the same reason as
true ? '0' : false would return a Character because it necessarily requires boxing, whereas true ? '0' : 0.0f would return a float because binary numeric promotion would occur.– Andy Turner
yesterday
I would imagine it is for the same reason as
true ? '0' : false would return a Character because it necessarily requires boxing, whereas true ? '0' : 0.0f would return a float because binary numeric promotion would occur.– Andy Turner
yesterday
1
1
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
yesterday
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
yesterday
add a comment |
1 Answer
1
active
oldest
votes
According to the switch expression's JEP, a switch expression is a poly expression:
A switch expression is a poly expression; if the target type is known, this type is pushed down into each arm. The type of a switch expression is its target type, if known; if not, a standalone type is computed by combining the types of each case arm.
Because you don't have a target type, the expression is not checked to match any given type, which is expected.
You can verify this by replacing var with a type:
int y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
case 3 -> true;
default -> 4;
;
In my shell, this fails with:
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from float to int
| case 1 -> 0.0F;
| ^--^
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from long to int
| case 2 -> 2L;
| ^^
| Error:
| incompatible types: bad type in switch expression
| boolean cannot be converted to int
| case 3 -> true;
| ^--^
But if you remove boolean:...
It should be enough to see how the standalone type is determined (rules here):
The type of a standalone switch expression is determined as follows:
- If the result expressions all have the same type (which may be the null type), then that is the type of the switch expression.
- Otherwise, if the type of each result expression is boolean or Boolean, an unboxing conversion (5.1.8) is applied to each result expression of type Boolean, and the switch expression has type boolean.
Otherwise, if the type of each result expression is convertible to a numeric type (5.1.8), the type of the switch expression is the result of numeric promotion (5.6) applied to the result expressions.
Otherwise, boxing conversion (5.1.7) is applied to each result expression that has a primitive type, after which the type of the switch expression is the result of applying capture conversion (5.1.10) to the least upper bound (4.10.4) of the types of the result expressions.
As far as I can see, when you remove the boolean expression, you're left with numeric expressions (char '0' (int 48) is promoted to float 48.0). See third bullet point above.
And as for why float is the result's type, see the Numeric Contexts section.
4
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
yesterday
why the first output gives youjava.lang.Characterclass? because boolean is after a float class. why float is not casting?
– Akash Shah
yesterday
2
@AkashShah I believe it's because no type conversion occurs. I haven't verified this, but I think the least upper bound for all these expression's types isjava.lang.Object. So it boils down to something likeObject y = ...and the actual type of the result ends up being printed (java.lang.Characterbeing the boxed type of the matched case expression, which returns'0')
– ernest_k
yesterday
4
@Ilya no, when you usevar, there is no target type. In that case, the right-hand side has to be treated as stand-alone expression (not poly expression), to determine the expression type, then, the variable will get the resulting type. As said by Andy Turner, the behavior is consistent with previous Java versions. The takeaway is, when the type is not obvious, don’t usevarto declare a variable.
– Holger
yesterday
3
@Ilya no, in the first example, the variable’s type is an intersection type ofObject,Serializable, andComparable<?>. If you wantObject(which would be relevant if you want to assign another value at a later point), you have to declare it explicitly. Your question’s example is equivalent tovar y = x == 0? '0': x == 1? 0.0F: x == 2? 2L: x == 3? true: 4;. As said, usevarwhen the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
yesterday
|
show 3 more comments
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55294208%2fwhy-does-java-12-try-to-convert-the-result-of-a-switch-to-a-number%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
According to the switch expression's JEP, a switch expression is a poly expression:
A switch expression is a poly expression; if the target type is known, this type is pushed down into each arm. The type of a switch expression is its target type, if known; if not, a standalone type is computed by combining the types of each case arm.
Because you don't have a target type, the expression is not checked to match any given type, which is expected.
You can verify this by replacing var with a type:
int y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
case 3 -> true;
default -> 4;
;
In my shell, this fails with:
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from float to int
| case 1 -> 0.0F;
| ^--^
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from long to int
| case 2 -> 2L;
| ^^
| Error:
| incompatible types: bad type in switch expression
| boolean cannot be converted to int
| case 3 -> true;
| ^--^
But if you remove boolean:...
It should be enough to see how the standalone type is determined (rules here):
The type of a standalone switch expression is determined as follows:
- If the result expressions all have the same type (which may be the null type), then that is the type of the switch expression.
- Otherwise, if the type of each result expression is boolean or Boolean, an unboxing conversion (5.1.8) is applied to each result expression of type Boolean, and the switch expression has type boolean.
Otherwise, if the type of each result expression is convertible to a numeric type (5.1.8), the type of the switch expression is the result of numeric promotion (5.6) applied to the result expressions.
Otherwise, boxing conversion (5.1.7) is applied to each result expression that has a primitive type, after which the type of the switch expression is the result of applying capture conversion (5.1.10) to the least upper bound (4.10.4) of the types of the result expressions.
As far as I can see, when you remove the boolean expression, you're left with numeric expressions (char '0' (int 48) is promoted to float 48.0). See third bullet point above.
And as for why float is the result's type, see the Numeric Contexts section.
4
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
yesterday
why the first output gives youjava.lang.Characterclass? because boolean is after a float class. why float is not casting?
– Akash Shah
yesterday
2
@AkashShah I believe it's because no type conversion occurs. I haven't verified this, but I think the least upper bound for all these expression's types isjava.lang.Object. So it boils down to something likeObject y = ...and the actual type of the result ends up being printed (java.lang.Characterbeing the boxed type of the matched case expression, which returns'0')
– ernest_k
yesterday
4
@Ilya no, when you usevar, there is no target type. In that case, the right-hand side has to be treated as stand-alone expression (not poly expression), to determine the expression type, then, the variable will get the resulting type. As said by Andy Turner, the behavior is consistent with previous Java versions. The takeaway is, when the type is not obvious, don’t usevarto declare a variable.
– Holger
yesterday
3
@Ilya no, in the first example, the variable’s type is an intersection type ofObject,Serializable, andComparable<?>. If you wantObject(which would be relevant if you want to assign another value at a later point), you have to declare it explicitly. Your question’s example is equivalent tovar y = x == 0? '0': x == 1? 0.0F: x == 2? 2L: x == 3? true: 4;. As said, usevarwhen the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
yesterday
|
show 3 more comments
According to the switch expression's JEP, a switch expression is a poly expression:
A switch expression is a poly expression; if the target type is known, this type is pushed down into each arm. The type of a switch expression is its target type, if known; if not, a standalone type is computed by combining the types of each case arm.
Because you don't have a target type, the expression is not checked to match any given type, which is expected.
You can verify this by replacing var with a type:
int y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
case 3 -> true;
default -> 4;
;
In my shell, this fails with:
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from float to int
| case 1 -> 0.0F;
| ^--^
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from long to int
| case 2 -> 2L;
| ^^
| Error:
| incompatible types: bad type in switch expression
| boolean cannot be converted to int
| case 3 -> true;
| ^--^
But if you remove boolean:...
It should be enough to see how the standalone type is determined (rules here):
The type of a standalone switch expression is determined as follows:
- If the result expressions all have the same type (which may be the null type), then that is the type of the switch expression.
- Otherwise, if the type of each result expression is boolean or Boolean, an unboxing conversion (5.1.8) is applied to each result expression of type Boolean, and the switch expression has type boolean.
Otherwise, if the type of each result expression is convertible to a numeric type (5.1.8), the type of the switch expression is the result of numeric promotion (5.6) applied to the result expressions.
Otherwise, boxing conversion (5.1.7) is applied to each result expression that has a primitive type, after which the type of the switch expression is the result of applying capture conversion (5.1.10) to the least upper bound (4.10.4) of the types of the result expressions.
As far as I can see, when you remove the boolean expression, you're left with numeric expressions (char '0' (int 48) is promoted to float 48.0). See third bullet point above.
And as for why float is the result's type, see the Numeric Contexts section.
4
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
yesterday
why the first output gives youjava.lang.Characterclass? because boolean is after a float class. why float is not casting?
– Akash Shah
yesterday
2
@AkashShah I believe it's because no type conversion occurs. I haven't verified this, but I think the least upper bound for all these expression's types isjava.lang.Object. So it boils down to something likeObject y = ...and the actual type of the result ends up being printed (java.lang.Characterbeing the boxed type of the matched case expression, which returns'0')
– ernest_k
yesterday
4
@Ilya no, when you usevar, there is no target type. In that case, the right-hand side has to be treated as stand-alone expression (not poly expression), to determine the expression type, then, the variable will get the resulting type. As said by Andy Turner, the behavior is consistent with previous Java versions. The takeaway is, when the type is not obvious, don’t usevarto declare a variable.
– Holger
yesterday
3
@Ilya no, in the first example, the variable’s type is an intersection type ofObject,Serializable, andComparable<?>. If you wantObject(which would be relevant if you want to assign another value at a later point), you have to declare it explicitly. Your question’s example is equivalent tovar y = x == 0? '0': x == 1? 0.0F: x == 2? 2L: x == 3? true: 4;. As said, usevarwhen the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
yesterday
|
show 3 more comments
According to the switch expression's JEP, a switch expression is a poly expression:
A switch expression is a poly expression; if the target type is known, this type is pushed down into each arm. The type of a switch expression is its target type, if known; if not, a standalone type is computed by combining the types of each case arm.
Because you don't have a target type, the expression is not checked to match any given type, which is expected.
You can verify this by replacing var with a type:
int y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
case 3 -> true;
default -> 4;
;
In my shell, this fails with:
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from float to int
| case 1 -> 0.0F;
| ^--^
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from long to int
| case 2 -> 2L;
| ^^
| Error:
| incompatible types: bad type in switch expression
| boolean cannot be converted to int
| case 3 -> true;
| ^--^
But if you remove boolean:...
It should be enough to see how the standalone type is determined (rules here):
The type of a standalone switch expression is determined as follows:
- If the result expressions all have the same type (which may be the null type), then that is the type of the switch expression.
- Otherwise, if the type of each result expression is boolean or Boolean, an unboxing conversion (5.1.8) is applied to each result expression of type Boolean, and the switch expression has type boolean.
Otherwise, if the type of each result expression is convertible to a numeric type (5.1.8), the type of the switch expression is the result of numeric promotion (5.6) applied to the result expressions.
Otherwise, boxing conversion (5.1.7) is applied to each result expression that has a primitive type, after which the type of the switch expression is the result of applying capture conversion (5.1.10) to the least upper bound (4.10.4) of the types of the result expressions.
As far as I can see, when you remove the boolean expression, you're left with numeric expressions (char '0' (int 48) is promoted to float 48.0). See third bullet point above.
And as for why float is the result's type, see the Numeric Contexts section.
According to the switch expression's JEP, a switch expression is a poly expression:
A switch expression is a poly expression; if the target type is known, this type is pushed down into each arm. The type of a switch expression is its target type, if known; if not, a standalone type is computed by combining the types of each case arm.
Because you don't have a target type, the expression is not checked to match any given type, which is expected.
You can verify this by replacing var with a type:
int y = switch (0)
case 0 -> '0';
case 1 -> 0.0F;
case 2 -> 2L;
case 3 -> true;
default -> 4;
;
In my shell, this fails with:
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from float to int
| case 1 -> 0.0F;
| ^--^
| Error:
| incompatible types: bad type in switch expression
| possible lossy conversion from long to int
| case 2 -> 2L;
| ^^
| Error:
| incompatible types: bad type in switch expression
| boolean cannot be converted to int
| case 3 -> true;
| ^--^
But if you remove boolean:...
It should be enough to see how the standalone type is determined (rules here):
The type of a standalone switch expression is determined as follows:
- If the result expressions all have the same type (which may be the null type), then that is the type of the switch expression.
- Otherwise, if the type of each result expression is boolean or Boolean, an unboxing conversion (5.1.8) is applied to each result expression of type Boolean, and the switch expression has type boolean.
Otherwise, if the type of each result expression is convertible to a numeric type (5.1.8), the type of the switch expression is the result of numeric promotion (5.6) applied to the result expressions.
Otherwise, boxing conversion (5.1.7) is applied to each result expression that has a primitive type, after which the type of the switch expression is the result of applying capture conversion (5.1.10) to the least upper bound (4.10.4) of the types of the result expressions.
As far as I can see, when you remove the boolean expression, you're left with numeric expressions (char '0' (int 48) is promoted to float 48.0). See third bullet point above.
And as for why float is the result's type, see the Numeric Contexts section.
edited yesterday
answered yesterday
ernest_kernest_k
24.1k43050
24.1k43050
4
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
yesterday
why the first output gives youjava.lang.Characterclass? because boolean is after a float class. why float is not casting?
– Akash Shah
yesterday
2
@AkashShah I believe it's because no type conversion occurs. I haven't verified this, but I think the least upper bound for all these expression's types isjava.lang.Object. So it boils down to something likeObject y = ...and the actual type of the result ends up being printed (java.lang.Characterbeing the boxed type of the matched case expression, which returns'0')
– ernest_k
yesterday
4
@Ilya no, when you usevar, there is no target type. In that case, the right-hand side has to be treated as stand-alone expression (not poly expression), to determine the expression type, then, the variable will get the resulting type. As said by Andy Turner, the behavior is consistent with previous Java versions. The takeaway is, when the type is not obvious, don’t usevarto declare a variable.
– Holger
yesterday
3
@Ilya no, in the first example, the variable’s type is an intersection type ofObject,Serializable, andComparable<?>. If you wantObject(which would be relevant if you want to assign another value at a later point), you have to declare it explicitly. Your question’s example is equivalent tovar y = x == 0? '0': x == 1? 0.0F: x == 2? 2L: x == 3? true: 4;. As said, usevarwhen the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
yesterday
|
show 3 more comments
4
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
yesterday
why the first output gives youjava.lang.Characterclass? because boolean is after a float class. why float is not casting?
– Akash Shah
yesterday
2
@AkashShah I believe it's because no type conversion occurs. I haven't verified this, but I think the least upper bound for all these expression's types isjava.lang.Object. So it boils down to something likeObject y = ...and the actual type of the result ends up being printed (java.lang.Characterbeing the boxed type of the matched case expression, which returns'0')
– ernest_k
yesterday
4
@Ilya no, when you usevar, there is no target type. In that case, the right-hand side has to be treated as stand-alone expression (not poly expression), to determine the expression type, then, the variable will get the resulting type. As said by Andy Turner, the behavior is consistent with previous Java versions. The takeaway is, when the type is not obvious, don’t usevarto declare a variable.
– Holger
yesterday
3
@Ilya no, in the first example, the variable’s type is an intersection type ofObject,Serializable, andComparable<?>. If you wantObject(which would be relevant if you want to assign another value at a later point), you have to declare it explicitly. Your question’s example is equivalent tovar y = x == 0? '0': x == 1? 0.0F: x == 2? 2L: x == 3? true: 4;. As said, usevarwhen the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
yesterday
4
4
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
yesterday
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
yesterday
why the first output gives you
java.lang.Character class? because boolean is after a float class. why float is not casting?– Akash Shah
yesterday
why the first output gives you
java.lang.Character class? because boolean is after a float class. why float is not casting?– Akash Shah
yesterday
2
2
@AkashShah I believe it's because no type conversion occurs. I haven't verified this, but I think the least upper bound for all these expression's types is
java.lang.Object. So it boils down to something like Object y = ... and the actual type of the result ends up being printed (java.lang.Character being the boxed type of the matched case expression, which returns '0')– ernest_k
yesterday
@AkashShah I believe it's because no type conversion occurs. I haven't verified this, but I think the least upper bound for all these expression's types is
java.lang.Object. So it boils down to something like Object y = ... and the actual type of the result ends up being printed (java.lang.Character being the boxed type of the matched case expression, which returns '0')– ernest_k
yesterday
4
4
@Ilya no, when you use
var, there is no target type. In that case, the right-hand side has to be treated as stand-alone expression (not poly expression), to determine the expression type, then, the variable will get the resulting type. As said by Andy Turner, the behavior is consistent with previous Java versions. The takeaway is, when the type is not obvious, don’t use var to declare a variable.– Holger
yesterday
@Ilya no, when you use
var, there is no target type. In that case, the right-hand side has to be treated as stand-alone expression (not poly expression), to determine the expression type, then, the variable will get the resulting type. As said by Andy Turner, the behavior is consistent with previous Java versions. The takeaway is, when the type is not obvious, don’t use var to declare a variable.– Holger
yesterday
3
3
@Ilya no, in the first example, the variable’s type is an intersection type of
Object,Serializable, and Comparable<?>. If you want Object (which would be relevant if you want to assign another value at a later point), you have to declare it explicitly. Your question’s example is equivalent to var y = x == 0? '0': x == 1? 0.0F: x == 2? 2L: x == 3? true: 4;. As said, use var when the right-hand side is obvious only. No-one forces you to use it at other places.– Holger
yesterday
@Ilya no, in the first example, the variable’s type is an intersection type of
Object,Serializable, and Comparable<?>. If you want Object (which would be relevant if you want to assign another value at a later point), you have to declare it explicitly. Your question’s example is equivalent to var y = x == 0? '0': x == 1? 0.0F: x == 2? 2L: x == 3? true: 4;. As said, use var when the right-hand side is obvious only. No-one forces you to use it at other places.– Holger
yesterday
|
show 3 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55294208%2fwhy-does-java-12-try-to-convert-the-result-of-a-switch-to-a-number%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Probably some kind of optimization. In the second example you can map all results to Float, in the first example they are just only Objects.
– Ralf Renz
yesterday
9
I would imagine it is for the same reason as
true ? '0' : falsewould return a Character because it necessarily requires boxing, whereastrue ? '0' : 0.0fwould return a float because binary numeric promotion would occur.– Andy Turner
yesterday
1
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
yesterday