三元运算符返回意外的输出

This subject is already asked but I didn't understand it. You'll find my program below. When I run this program it prints X and 88. When I remove do the declaration of int i = 0 it returns X and X. I found some explanations here : Unexpected output when using a ternary operator and final variable but i didn't understand it so much. I don't understand why this program returns X and 88 instead of X and X.

public class Ternary {
    public static void main(String[] args) {
        char x = 'X';
        int i = 0;
        System.out.println(true  ? x : 0);
        System.out.println(false ? i : x);
    }
}
评论
  • ut_quo
    ut_quo 回复

    该声明

    System.out.println(true  ? x : 0);
    

    可以写成

    if(true) {
        System.out.println(x);
    } else {
        System.out.println(0);
    }
    

    which will print X

    同样,声明

    System.out.println(false ? i : x);
    

    可以写成

    if(false) {
        System.out.println(i);
    } else {
        System.out.println(x);
    }
    

    which will print X

    Thus, the output is X and X.

  • 蛋小疼
    蛋小疼 回复

    Both paths through the ternary must be of the same type. char can (and is) widened to an int yielding the ascii value 88 instead of X.

    System.out.println(false ? (char) i : x);
    

    而且两者都将输出

    X
    X