One of the least understood, and most underestimated Java language constructs is the ?: operator. Most people never even seen it in action. And those who did, never actually used it to do anything meaningful. Imagine something like this:
public generateFoo(int threshold)
{
if(threshold > MIN_THRESHOLD)
return new Foo();
else
return null;
}
In this snippet of code we have a function which generates a new Foo object if the passed argument is greater than some minimal threshold. If it is below threshold we return null. This is not an uncommon scenario… But with the ?: operator we could accomplish all of this on a single line.
public generateFoo(in threshold)
{
return (threshold > MIN_THRESHOLD) ? new Foo() : null;
}
If you didn’t catch that let me show you something simpler:
int foo = bar ? a : b;
Java expects to a boolean or an expression evaluating to a boolean before the question mark. If that expression is true, then the whole statement evaluates to a. Else it evaluates to b.
It is elegant, produces a lean code and saves you one return statement. It is a good coding practice to have one return statement per method when possible. I think more Java programmers should embrace this little syntactic sugar. It saves you allot of typing when used appropriately.
Thanks for this!
I needed a good explanation, and you gave me one ;)
Cheers from Iceland.
public Playlist(Playlist playList){
if (playList != null){
for(int i = 0; i
Patrick – I think your comment got eaten. Remember, you can’t use the < and > unless you put them in the <pre> tag. Click the code button above the textbox. Observe:
Alternatively you can use the < and > HTML entities like I did above.
Also, preview button does wonders for you. ;)
thx, I’ll repost.
But with the question mark operator, it did not work.
Well, that is the one way you are not supposed to use the question mark statement. This statement is supposed to evaluate the boolean, and based on it’s value return the result of the statement to the left or the right of the colon.
In other words, the two statements are required to return a value. Since println() is void, I believe this syntax will throw error. So you are right, in your example, the if statement is definitely the correct approach.
To put it more simply, the question mark statement must evaluate to (or return) a value of some sort. It is not supposed to be used to perform an action.
I hope that makes sense. :)
Ya thanks, it make sense.
another advantage that it will not excute statement1:statement2 only the correct one
This works:
System.out.println(boolean ? “Some text” : “Some other text”);
Thanks for the clear explanation :)
Thanks, I understand this!
Nice explanation, thanks.
Returning null makes Baby Jesus cry.
Thanks, you turned Chinese into something understandable ;-)
instead of
int foo = bar ? a : b;
this
var== expression ? a: b;