Alex Rivera | Logout

Can I null-check in-line?

Asked 2012-09-10T07:44:39.330
11

I have a Java command that looks something like below:

Foo f = new Foo();
String string = f.format(new Bar().getSelection());
                       // ^ may be null

Sometimes it's possible that my Bar object returns null, this is by design.

To me, the natural thing to do is to split the commands into multiple lines and do a null-check separately, such as:

Foo f = new Foo();
BarSel bs = new Bar().getSelection();
String string = "";
if (bs != null) {
    string = f.format(bs);
    // continue...
}

However, I'm wondering if there is a way to do this in one line? Is it possible to null-check objects inline?

I seem to remember reading about being able to use question mark, but I can't recall the exact syntax and I might be wrong about that. Note that I'm not referring to the ternary operator, although that is another valid approach.

Edit
Report

1 Answer

0
Foo f = new Foo();
BarSel bs = new Bar().getSelection();
String string = bs != null ? f.format(bs) : "";
answered 2012-09-10T07:48:44.240

Your Answer