Can we use command in ternary operator (Java)?

天大地大妈咪最大 提交于 2020-12-27 07:20:12

问题


This is a working code:

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

But it isn't:

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

Why?


回答1:


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.




回答2:


The ternary operator should always return a value, whereas in case of SysOut the return type is void.



来源:https://stackoverflow.com/questions/59875556/can-we-use-command-in-ternary-operator-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!