Why the following code prints false?

时间:2015-06-15 14:59:16

标签: java

can any one please explain me why the following code prints false

    public class Test {
public static void main(String[] args) {

    System.out.println(true?false:true == true?false:true);
}
}

2 个答案:

答案 0 :(得分:3)

Since the first condition is true, it will print false.

edit:

That is using the ternary operator, basically it is a simplified if.

       if (true) {
           System.out.println(false);
       } else {
           if (true == true) {
               System.out.println(false);
           } else {
               System.out.println(false);
           }
           System.out.println(true);
       }

using the ternary operator, this can be simplified as

System.out.println(true?false:true == true?false:true);

so the post above uses the same operation using true or false.

答案 1 :(得分:2)

true?false:true == true?false:true is evaluated from left to right, so it's equivalent to true?false:(true == true?false:true). Since true is true, the first ternary expression returns false, which is the printed output.