Why does the narrowing conversion from int to short not work if local variable is used in the ternary operator
Asked Answered
B

1

9

The following line of code is accepted by the compiler (sun-jdk-8u51) without any warnings or errors:

short b = true ? 1 : 1;

Whereas the next two code lines lead to a compilation error (incompatible types: possible lossy conversion from int to short):

boolean bool = true;
short s = bool ? 1 : 1;

Why is the compiler not able to perform the same narrowing conversion of the primitive integer 1 in the second case?

Bridie answered 11/11, 2015 at 12:18 Comment(9)
This is because in the first case, since true is a compile time constant, the whole expression is evaluated during compile time, so you basically have short b = 1; whereas in the second version, the compiler does not do the simplification for you, hence the error.Gustie
Related (possibly dupe): #4711931Gustie
assignment conversion - if the expression is a constant expression ... narrowing primitive conversion may be used ...Pedestal
groups.google.com/forum/#!topic/java-lang-fans/0zGzPygyJSUPedestal
@Gustie Couldn't you make this an answer?Hydrocele
@exilit, it would basically be a copy of Jon Skeet's answer over here. I'd prefer to close this as a dup tbh.Gustie
@Gustie Didn't see your second comment, sorry. You are right.Hydrocele
@aioobe: I don't think it's an dupe to the question Jon Skeet answered. I found a potential explanation in the section 15.25 of the specification: If the value of the first operand is true, then the second operand expression is chosen. For me this sounds pretty inline to the explanation you provided in your first comment and I'd recommend making this an answer to my question. IMO Jon's answer is lacking the influence of the first operand on the ternary operator, on which my question focus.Bridie
@Bridie you can always answer your own question and cite the conversation in the comments.Reverberate
B
3

As outlined by @aioobe in the comments:

This is because in the first case, since true is a compile time constant, the whole expression is evaluated during compile time, so you basically have short b = 1; whereas in the second version, the compiler does not do the simplification for you, hence the error

Adding final to the declaration of the variable bool makes it a constant variable, which also allows the compiler to interpret the code as mentioned above.

final boolean bool = true;
short s = bool ? 1 : 1;

See section 4.12.4

Bridie answered 28/11, 2016 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.