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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With