简体   繁体   English

什么样的Java语法是“== null?假:真;”

[英]What kind of Java syntax is “== null? false:true;”

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. 它必须是将返回的String从getParameter()转换为布尔值的东西。

But I've never seen this kind of Java with a questionmark and colon (except in a foreach loop). 但我从来没有见过这种带有问号和冒号的Java(除了在foreach循环中)。 Any hel appreciated! 任何帮助升值!

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)

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更清洁代码。

The ?: is an if you can have inside an expression. if您可以表达式内部使用?:

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

(go to ConditionalDemo2) (转到ConditionalDemo2)

It is shorthand for 这是简写

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

整件事情可能就是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM