简体   繁体   中英

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.

But I've never seen this kind of Java with a questionmark and colon (except in a foreach loop). 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.

The ?: is an if you can have inside an expression.

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

(go to ConditionalDemo2)

It is shorthand for

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

整件事情可能就是

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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