Why does Java 12 try to convert the result of a switch to a number? The Next CEO of Stack OverflowDoes 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”?

Can I calculate next year's exemptions based on this year's refund/amount owed?

What day is it again?

New carbon wheel brake pads after use on aluminum wheel?

Is a distribution that is normal, but highly skewed, considered Gaussian?

Audio Conversion With ADS1243

What steps are necessary to read a Modern SSD in Medieval Europe?

Decide between Polyglossia and Babel for LuaLaTeX in 2019

How to get the last not-null value in an ordered column of a huge table?

Does Germany produce more waste than the US?

Where do students learn to solve polynomial equations these days?

Which one is the true statement?

Towers in the ocean; How deep can they be built?

Players Circumventing the limitations of Wish

Why doesn't UK go for the same deal Japan has with EU to resolve Brexit?

What was Carter Burkes job for "the company" in "Aliens"?

Is there a reasonable and studied concept of reduction between regular languages?

Deriving the equation for variance

How to properly draw diagonal line while using multicolumn inside tabular environment?

Regression vs Random Forest - Combination of features

what's the use of '% to gdp' type of variables?

Won the lottery - how do I keep the money?

How to set page number in right side in chapter title page?

Is dried pee considered dirt?

What CSS properties can the br tag have?



Why does Java 12 try to convert the result of a switch to a number?



The Next CEO of Stack OverflowDoes 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”?










38















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.










share|improve this question






















  • 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






  • 12





    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





    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















38















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.










share|improve this question






















  • 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






  • 12





    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





    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













38












38








38


4






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.










share|improve this question














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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 6:44









IlyaIlya

431312




431312












  • 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






  • 12





    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





    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






  • 12





    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





    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




12




12





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












1 Answer
1






active

oldest

votes


















43














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.






share|improve this answer




















  • 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 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





    @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





    @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





    @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












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
);



);













draft saved

draft discarded


















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









43














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.






share|improve this answer




















  • 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 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





    @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





    @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





    @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
















43














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.






share|improve this answer




















  • 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 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





    @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





    @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





    @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














43












43








43







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.






share|improve this answer















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.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 22 at 8:19

























answered Mar 22 at 8:07









ernest_kernest_k

24.4k43050




24.4k43050







  • 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 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





    @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





    @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





    @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













  • 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 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





    @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





    @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





    @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








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




















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Bruad Bilen | Luke uk diar | NawigatsjuunCommonskategorii: BruadCommonskategorii: RunstükenWikiquote: Bruad

What is the offset in a seaplane's hull?

Slayer Innehåll Historia | Stil, komposition och lyrik | Bandets betydelse och framgångar | Sidoprojekt och samarbeten | Kontroverser | Medlemmar | Utmärkelser och nomineringar | Turnéer och festivaler | Diskografi | Referenser | Externa länkar | Navigeringsmenywww.slayer.net”Metal Massacre vol. 1””Metal Massacre vol. 3””Metal Massacre Volume III””Show No Mercy””Haunting the Chapel””Live Undead””Hell Awaits””Reign in Blood””Reign in Blood””Gold & Platinum – Reign in Blood””Golden Gods Awards Winners”originalet”Kerrang! Hall Of Fame””Slayer Looks Back On 37-Year Career In New Video Series: Part Two””South of Heaven””Gold & Platinum – South of Heaven””Seasons in the Abyss””Gold & Platinum - Seasons in the Abyss””Divine Intervention””Divine Intervention - Release group by Slayer””Gold & Platinum - Divine Intervention””Live Intrusion””Undisputed Attitude””Abolish Government/Superficial Love””Release “Slatanic Slaughter: A Tribute to Slayer” by Various Artists””Diabolus in Musica””Soundtrack to the Apocalypse””God Hates Us All””Systematic - Relationships””War at the Warfield””Gold & Platinum - War at the Warfield””Soundtrack to the Apocalypse””Gold & Platinum - Still Reigning””Metallica, Slayer, Iron Mauden Among Winners At Metal Hammer Awards””Eternal Pyre””Eternal Pyre - Slayer release group””Eternal Pyre””Metal Storm Awards 2006””Kerrang! Hall Of Fame””Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Bullet-For My Valentine booed at Metal Hammer Golden Gods Awards””Unholy Aliance””The End Of Slayer?””Slayer: We Could Thrash Out Two More Albums If We're Fast Enough...””'The Unholy Alliance: Chapter III' UK Dates Added”originalet”Megadeth And Slayer To Co-Headline 'Canadian Carnage' Trek”originalet”World Painted Blood””Release “World Painted Blood” by Slayer””Metallica Heading To Cinemas””Slayer, Megadeth To Join Forces For 'European Carnage' Tour - Dec. 18, 2010”originalet”Slayer's Hanneman Contracts Acute Infection; Band To Bring In Guest Guitarist””Cannibal Corpse's Pat O'Brien Will Step In As Slayer's Guest Guitarist”originalet”Slayer’s Jeff Hanneman Dead at 49””Dave Lombardo Says He Made Only $67,000 In 2011 While Touring With Slayer””Slayer: We Do Not Agree With Dave Lombardo's Substance Or Timeline Of Events””Slayer Welcomes Drummer Paul Bostaph Back To The Fold””Slayer Hope to Unveil Never-Before-Heard Jeff Hanneman Material on Next Album””Slayer Debut New Song 'Implode' During Surprise Golden Gods Appearance””Release group Repentless by Slayer””Repentless - Slayer - Credits””Slayer””Metal Storm Awards 2015””Slayer - to release comic book "Repentless #1"””Slayer To Release 'Repentless' 6.66" Vinyl Box Set””BREAKING NEWS: Slayer Announce Farewell Tour””Slayer Recruit Lamb of God, Anthrax, Behemoth + Testament for Final Tour””Slayer lägger ner efter 37 år””Slayer Announces Second North American Leg Of 'Final' Tour””Final World Tour””Slayer Announces Final European Tour With Lamb of God, Anthrax And Obituary””Slayer To Tour Europe With Lamb of God, Anthrax And Obituary””Slayer To Play 'Last French Show Ever' At Next Year's Hellfst””Slayer's Final World Tour Will Extend Into 2019””Death Angel's Rob Cavestany On Slayer's 'Farewell' Tour: 'Some Of Us Could See This Coming'””Testament Has No Plans To Retire Anytime Soon, Says Chuck Billy””Anthrax's Scott Ian On Slayer's 'Farewell' Tour Plans: 'I Was Surprised And I Wasn't Surprised'””Slayer””Slayer's Morbid Schlock””Review/Rock; For Slayer, the Mania Is the Message””Slayer - Biography””Slayer - Reign In Blood”originalet”Dave Lombardo””An exclusive oral history of Slayer”originalet”Exclusive! Interview With Slayer Guitarist Jeff Hanneman”originalet”Thinking Out Loud: Slayer's Kerry King on hair metal, Satan and being polite””Slayer Lyrics””Slayer - Biography””Most influential artists for extreme metal music””Slayer - Reign in Blood””Slayer guitarist Jeff Hanneman dies aged 49””Slatanic Slaughter: A Tribute to Slayer””Gateway to Hell: A Tribute to Slayer””Covered In Blood””Slayer: The Origins of Thrash in San Francisco, CA.””Why They Rule - #6 Slayer”originalet”Guitar World's 100 Greatest Heavy Metal Guitarists Of All Time”originalet”The fans have spoken: Slayer comes out on top in readers' polls”originalet”Tribute to Jeff Hanneman (1964-2013)””Lamb Of God Frontman: We Sound Like A Slayer Rip-Off””BEHEMOTH Frontman Pays Tribute To SLAYER's JEFF HANNEMAN””Slayer, Hatebreed Doing Double Duty On This Year's Ozzfest””System of a Down””Lacuna Coil’s Andrea Ferro Talks Influences, Skateboarding, Band Origins + More””Slayer - Reign in Blood””Into The Lungs of Hell””Slayer rules - en utställning om fans””Slayer and Their Fans Slashed Through a No-Holds-Barred Night at Gas Monkey””Home””Slayer””Gold & Platinum - The Big 4 Live from Sofia, Bulgaria””Exclusive! Interview With Slayer Guitarist Kerry King””2008-02-23: Wiltern, Los Angeles, CA, USA””Slayer's Kerry King To Perform With Megadeth Tonight! - Oct. 21, 2010”originalet”Dave Lombardo - Biography”Slayer Case DismissedArkiveradUltimate Classic Rock: Slayer guitarist Jeff Hanneman dead at 49.”Slayer: "We could never do any thing like Some Kind Of Monster..."””Cannibal Corpse'S Pat O'Brien Will Step In As Slayer'S Guest Guitarist | The Official Slayer Site”originalet”Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Kerrang! Awards 2006 Blog: Kerrang! Hall Of Fame””Kerrang! Awards 2013: Kerrang! Legend”originalet”Metallica, Slayer, Iron Maien Among Winners At Metal Hammer Awards””Metal Hammer Golden Gods Awards””Bullet For My Valentine Booed At Metal Hammer Golden Gods Awards””Metal Storm Awards 2006””Metal Storm Awards 2015””Slayer's Concert History””Slayer - Relationships””Slayer - Releases”Slayers officiella webbplatsSlayer på MusicBrainzOfficiell webbplatsSlayerSlayerr1373445760000 0001 1540 47353068615-5086262726cb13906545x(data)6033143kn20030215029