什么样的 Java 语法是“== null?false:true;”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3403562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:58:49  来源:igfitidea点击:

What kind of Java syntax is "== null? false:true;"

java

提问by tzippy

I am looking through code and wondering what this means:

我正在查看代码并想知道这意味着什么:

Boolean foo = request.getParameter("foo") == null? false:true;

It's gotta be something that converts the returning String from getParameter() into a Boolean.

它必须是将 getParameter() 返回的 String 转换为布尔值的东西。

But I've never seen this kind of Java with a questionmark and colon (except in a foreach loop). Any hel appreciated!

但我从未见过这种带有问号和冒号的 Java(除了在 foreach 循环中)。任何人都表示赞赏!

采纳答案by paxdiablo

It's the ternary operator. The snippet:

这是三元运算符。片段:

Boolean foo = request.getParameter("foo") == null? false:true;

is equivalent to:

相当于:

Boolean foo;
if (request.getParameter("foo") == null)
    foo = false;
else
    foo = true;

or (optimised):

或(优化):

Boolean foo = request.getParameter("foo") != null;

The basic form of the operator is along the lines of:

运算符的基本形式如下:

(condition) ? (value if condition true) : (value if condition false)

回答by NullUserException

That's the ternary operator:

那是三元运算符:

(condition) ? if-true : if-false

The whole thing could've been written as:

整个事情可以写成:

Boolean foo = request.getParameter("foo") != null;

Which IMO is cleaner code.

哪个 IMO 是更干净的代码。

回答by Zaki

It is shorthand for

它是简写

Boolean foo;
if(request.getParameter("foo")==null)
{
 foo = false;
}
else { foo = true; }

回答by Thorbj?rn Ravn Andersen

The ?:is an ifyou can have insidean expression.

?:if你可以有内部的表达式。

The Java Tutorial describes it here: http://download-llnw.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

Java 教程在这里对其进行了描述:http: //download-llnw.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

(go to ConditionalDemo2)

(转到 ConditionalDemo2)

回答by kocka

The whole thing could be just

整件事可能只是

Boolean foo = (request.getParameter("foo") != null);