Jump to content

Java syntax: (condition ? something : something) what does it do?

Go to solution Solved by Nuluvius,

Hi. 

I have come across some notation in Java that I don't understand what means:

 

	Obj o1, o2 = null;
    	(...)
        o1 = (o2 != null ? o2 : o1);

        

What does that last line do? 

To me, it looks like the form is: (condition ? something : something)

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to post
Share on other sites

3 minutes ago, mariushm said:

If you want to really confuse someone then yes.


 


function isFalse ($value) {

return ($value==FALSE) ? TRUE : FALSE;

}

would probably be a better example (in PHP above).

 

I don't know PHP, but I could make it less confusing:

 

result = a > b ? a : b;

does this:

if (a > b)
	result = a;
else
	result = b;

Am I correct?

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to post
Share on other sites

Just now, Dat Guy said:

Actually, that would be a horrible example because it is an unnecessarily verbose wording for "return !$value".

Well, yes and no. It was a bad example. I modified the example to be more correct.

 

In PHP you don't have to specify data type for each variable, so some variables are converted to boolean by some rules which you may or may not agree with. See http://php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

I've changed the example code to do strict checking and be more correct. Using  !$variable would just do a plain == comparison internally, so an empty array for example could return FALSE which you may not want.

 

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×