Quick question: What exactly does this line of code do?

Started by
3 comments, last by DevFred 15 years, 2 months ago
Hi, I've come across statements like this in other people's code several times but never really understood what exactly it was doing:
if (customer != null ? !customer.equals(order.customer) : order.customer != null)
(This is Java by the way) I understand that overall it's a boolean statement, and it's comprised of three other boolean statements. I think I understand generally what program state it is testing for, but what exactly are the question mark and colon symbols doing? I've only ever used symbols like || or && in my own boolean statements. Thanks! [smile]
http://www.thomaswiggins.co.uk (under construction)
Advertisement
can be translated to:

bool stuff;if( customer != null )   stuff = !customer.equals(order.customer);else   stuff = order.customer != null;if( stuff ){    // do stuff}
The "op1 ? op2 : op3" form is called the ternary operatory. In short it means "if op1 is true then return op2 else return op3". Read more about it here.
Ahh, okay. I understand. Thanks a lot guys! [smile]
http://www.thomaswiggins.co.uk (under construction)
Quiz time! What does the following program print?
Object x = (1 < 2) ? new Integer(1) : new Float(2);System.out.println(x);

a) 1
b) 2.0
c) throws an exception
d) none of the above

If you like this kind of stuff, check out
>Java Puzzlers.

This topic is closed to new replies.

Advertisement