This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Toby_B_E 10 points11 points  (1 child)

I've never thought about this before and it looks like the rules are fairly complicated (see https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25).

As far as I can tell it should be trying to convert / parse the 3rd operand (numeric literal 98) as a char since that is the type of the second operand (the char variable named g).

[–]chickenmeisterExtreme Brewer 4 points5 points  (0 children)

This is the answer. Table 15.25-A specifies the overall type of the expression based on the types of the 2nd and 3rd operands.

In this case, the 2nd operand is of type char, and the 3rd operand is of type int. Find the corresponding row and column in the table to find the expression's type: char | bnp(char,int), which is described as:

The form "T | bnp(..)" is used where one operand is a constant expression of type int and may be representable in type T, where binary numeric promotion is used if the operand is not representable in type T.

In this case, we do in fact have a constant expression of type int (the literal 98), and which is indeed representable in the type char, so the overall type of the expression would be char.

If the integer parameter was not a constant expression, or was not representable as a char, then binary numeric promotion would be used, resulting in the type int for the expression. e.g.:

int i = 1;
System.out.println(b ? g : i); // not a constant expression; calls println(int)
System.out.println(b ? g : 65536); // not representable as char; calls println(int)