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”?
Possibly bubble sort algorithm
If Manufacturer spice model and Datasheet give different values which should I use?
The use of multiple foreign keys on same column in SQL Server
Infinite past with a beginning?
How does one intimidate enemies without having the capacity for violence?
New order #4: World
Why is this code 6.5x slower with optimizations enabled?
Is it tax fraud for an individual to declare non-taxable revenue as taxable income? (US tax laws)
Why is an old chain unsafe?
I probably found a bug with the sudo apt install function
Shell script can be run only with sh command
What is the command to reset a PC without deleting any files
Set-theoretical foundations of Mathematics with only bounded quantifiers
A function which translates a sentence to title-case
Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)
Patience, young "Padovan"
Can a German sentence have two subjects?
Why did the Germans forbid the possession of pet pigeons in Rostov-on-Don in 1941?
How can bays and straits be determined in a procedurally generated map?
Banach space and Hilbert space topology
Can I interfere when another PC is about to be attacked?
Email Account under attack (really) - anything I can do?
Download, install and reboot computer at night if needed
Motorized valve interfering with button?
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”?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
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
Mar 22 at 7:03
13
I would imagine it is for the same reason astrue ? '0' : false
would return a Character because it necessarily requires boxing, whereastrue ? '0' : 0.0f
would return a float because binary numeric promotion would occur.
– Andy Turner
Mar 22 at 7:16
3
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
Mar 22 at 7:28
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 Mar 22 at 6:44
IlyaIlya
456312
456312
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
Mar 22 at 7:03
13
I would imagine it is for the same reason astrue ? '0' : false
would return a Character because it necessarily requires boxing, whereastrue ? '0' : 0.0f
would return a float because binary numeric promotion would occur.
– Andy Turner
Mar 22 at 7:16
3
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
Mar 22 at 7:28
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
Mar 22 at 7:03
13
I would imagine it is for the same reason astrue ? '0' : false
would return a Character because it necessarily requires boxing, whereastrue ? '0' : 0.0f
would return a float because binary numeric promotion would occur.
– Andy Turner
Mar 22 at 7:16
3
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
Mar 22 at 7:28
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
Mar 22 at 7:03
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
Mar 22 at 7:03
13
13
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
Mar 22 at 7:16
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
Mar 22 at 7:16
3
3
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
Mar 22 at 7:28
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
Mar 22 at 7:28
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.
7
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
Mar 22 at 8:35
why the first output gives youjava.lang.Character
class? because boolean is after a float class. why float is not casting?
– Akash Shah
Mar 22 at 8:41
5
@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.Character
being the boxed type of the matched case expression, which returns'0'
)
– ernest_k
Mar 22 at 8:46
7
@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 usevar
to declare a variable.
– Holger
Mar 22 at 10:38
6
@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, usevar
when the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
Mar 22 at 11:51
|
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.
7
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
Mar 22 at 8:35
why the first output gives youjava.lang.Character
class? because boolean is after a float class. why float is not casting?
– Akash Shah
Mar 22 at 8:41
5
@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.Character
being the boxed type of the matched case expression, which returns'0'
)
– ernest_k
Mar 22 at 8:46
7
@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 usevar
to declare a variable.
– Holger
Mar 22 at 10:38
6
@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, usevar
when the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
Mar 22 at 11:51
|
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.
7
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
Mar 22 at 8:35
why the first output gives youjava.lang.Character
class? because boolean is after a float class. why float is not casting?
– Akash Shah
Mar 22 at 8:41
5
@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.Character
being the boxed type of the matched case expression, which returns'0'
)
– ernest_k
Mar 22 at 8:46
7
@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 usevar
to declare a variable.
– Holger
Mar 22 at 10:38
6
@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, usevar
when the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
Mar 22 at 11:51
|
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 Mar 22 at 8:19
answered Mar 22 at 8:07
ernest_kernest_k
24.5k43050
24.5k43050
7
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
Mar 22 at 8:35
why the first output gives youjava.lang.Character
class? because boolean is after a float class. why float is not casting?
– Akash Shah
Mar 22 at 8:41
5
@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.Character
being the boxed type of the matched case expression, which returns'0'
)
– ernest_k
Mar 22 at 8:46
7
@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 usevar
to declare a variable.
– Holger
Mar 22 at 10:38
6
@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, usevar
when the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
Mar 22 at 11:51
|
show 3 more comments
7
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
Mar 22 at 8:35
why the first output gives youjava.lang.Character
class? because boolean is after a float class. why float is not casting?
– Akash Shah
Mar 22 at 8:41
5
@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.Character
being the boxed type of the matched case expression, which returns'0'
)
– ernest_k
Mar 22 at 8:46
7
@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 usevar
to declare a variable.
– Holger
Mar 22 at 10:38
6
@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, usevar
when the right-hand side is obvious only. No-one forces you to use it at other places.
– Holger
Mar 22 at 11:51
7
7
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
Mar 22 at 8:35
good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added.
– Eugene
Mar 22 at 8:35
why the first output gives you
java.lang.Character
class? because boolean is after a float class. why float is not casting?– Akash Shah
Mar 22 at 8:41
why the first output gives you
java.lang.Character
class? because boolean is after a float class. why float is not casting?– Akash Shah
Mar 22 at 8:41
5
5
@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
Mar 22 at 8:46
@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
Mar 22 at 8:46
7
7
@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
Mar 22 at 10:38
@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
Mar 22 at 10:38
6
6
@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
Mar 22 at 11:51
@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
Mar 22 at 11:51
|
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
Mar 22 at 7:03
13
I would imagine it is for the same reason as
true ? '0' : false
would return a Character because it necessarily requires boxing, whereastrue ? '0' : 0.0f
would return a float because binary numeric promotion would occur.– Andy Turner
Mar 22 at 7:16
3
Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" mentioned.
– Andy Turner
Mar 22 at 7:28