Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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!

like image 456
tzippy Avatar asked Aug 04 '10 07:08

tzippy


3 Answers

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)
like image 102
paxdiablo Avatar answered Nov 03 '22 00:11

paxdiablo


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.

like image 34
NullUserException Avatar answered Nov 02 '22 22:11

NullUserException


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)

like image 23
Thorbjørn Ravn Andersen Avatar answered Nov 03 '22 00:11

Thorbjørn Ravn Andersen