jastrachan | 7 Jul 14:47 2004

using || and && in a more clever way

John Rose made heaps of good suggestions during a face to face at 
JavaOne.  I'll try brain dump them to the mail lists and/or wiki over 
the coming weeks. This one's particularly cute.

x = a || b

would return either the value of a, if its coerced to a boolean and is 
true or the value of b. Right now null is false and non null is true. 
So if a or b could be null you could use the above to return the non 
null value.

A common requirement is if a value is null then use another value. So 
we could do

text = customer.name || "unknown"

to grab some text and if its null use some default value.

Similarly if we want to set a variable if its null we could replace 
code like this

if (x == null) {
     x = "foo"


x ||= "foo"

We could do similar things for && and &&= as well.