我们可以在三元运算符 (Java) 中使用命令吗? [英] Can we use command in ternary operator (Java)?

查看:49
本文介绍了我们可以在三元运算符 (Java) 中使用命令吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个工作代码:

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

但事实并非如此:

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

为什么?

推荐答案

A per 规范

第二个或第三个操作数表达式调用 void 方法是编译时错误.

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

println 是来自 PrintStream 类(System.out 是其实例)的方法,它的返回类型为 <代码>无效.

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;

如果你给一个方法返回 void(即没有)作为第二个和/或第三个表达式,运算符本身会返回什么?

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

最后,Java 没有称为命令"的词法结构.System.out.println 和其他方法一样是一个方法调用,它只是不返回任何东西.

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.

这篇关于我们可以在三元运算符 (Java) 中使用命令吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆