Can we use command in ternary operator (Java)?

后端 未结 2 1174
野的像风
野的像风 2021-01-29 13:05

This is a working code:

String a = \"first\";
String b = \"second\";
String object;
System.out.println(object != null ? a : b);

But it isn\'t:<

2条回答
  •  失恋的感觉
    2021-01-29 13:48

    A per the spec

    It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

    println is a method from the PrintStream class (which System.out is an instance of) and it has a return type of void.

    Consider that the operator itself is expected to return something for use in cases such as:

     bool a = true;
     int b = a ? 1 : 2;
    

    If you give a method returning void (i.e. nothing) as the second and/or third expression, what would the operator itself return?

    Finally, Java has no lexical structure that is called a "command". System.out.println is a method invocation like any other, it just doesn't return anything.

提交回复
热议问题