I'm looking at a piece of Java code that contains:
User rv = tmp != null && tmp.size() > 0 ? tmp.get(0) : null;
I'm not very strong with Java syntax. My interpretation is that rv = tmp as long as tmp is null tmp's size is > 0, or else it equals null. Am I correct?
4 Answers 4
Here is the "anatomy" of this expression:
rv = // assignment of a conditional expression
(tmp != null && tmp.size() > 0) // condition
? tmp.get(0) // on true
: null; // on false
This is a common way of ensuring that there would be no exception accessing element zero of the list: the condition ensures that tmp is not null, and also that the size is one or more.
2 Comments
It's a ternary conditional expression:
expr ? value-if-true : value-if-false
If expr is true, it evaluates to value-if-true, and otherwise it evaluates to value-if-valuse.
So, in this case, it's equivalent to:
if (tmp != null && tmp.size() > 0) {
rv = tmp.get(0);
} else {
rv = null;
}
Comments
rv = ((tmp != null && tmp.size() > 0) ? tmp.get(0) : null);
if expression inside the inner brackets return true then rv will hold the value tmp.get(0) else it will hold the value null.
variable = expression ? a : b ;
is similar to
if expression == true
variable = a;
else
variable =b ;
Comments
This is called a ternary statement.
Basically,
User rv = tmp != null && tmp.size() > 0 ? tmp.get(0) : null;
is a shorter way of writing:
User rv;
if (tmp != null && tmp.size() > 0)
rv = tmp.get(0);
else
rv = null;
The ternary statement is not faster. Although, in some cases, using it makes your code more readable.
User rv = (tmp != null && tmp.size() > 0) ? tmp.get(0) : null;