Unexpected output when using a ternary operator and final variable
Asked Answered
T

1

12

Consider this code snippet:

public static void main(String[] args) {
    int z1 = 0;
    final int z2 = 0;
    System.out.println(false ? z1 : 'X');
    System.out.println(false ? z2 : 'X');
}

When running this code, I would expect to see two X in your console. However, the real output is:

88
X

If we take a look at the Java specifications regarding the ternary operator, we found that

If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.

So the first output considers the 'X' char as an int, that's why it prints 88.

However, I am not sure to understand why the use of final changes the behavior for the second output.

Tarah answered 17/1, 2011 at 8:59 Comment(3)
Just as a side point, this is the second time today where I've seen someone effectively assume that what they expect to see is what everyone else expects to see. I think it would be more appropriate to say, "When running this code, I expected to see..."Darla
@Jon, you are right. Question edited.Tarah
groups.google.com/forum/#!topic/java-lang-fans/0zGzPygyJSUUndulate
D
9

In the second case, z2 counts as a constant expression, because it's a final variable of type int.

From section 4.12.4:

We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

Section 15.28 includes "constant variables" in the set of items which can be used to form a constant expression.

z1 is not a final variable (even though nothing else assigns a value to it) so it's not a constant variable, and thus not a constant expression - so the paragraph you quoted from the spec doesn't apply.

Darla answered 17/1, 2011 at 9:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.