Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I null-check in-line?

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.

like image 254
Redandwhite Avatar asked Sep 10 '12 07:09

Redandwhite


People also ask

How do you insert a null check?

How-to. Place your cursor on any parameter within the method. Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select the option to Add null checks for all parameters.

How do you check if a line is null?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

What are null checks?

A null indicates that a variable doesn't point to any object and holds no value. You can use a basic 'if' statement to check a null in a piece of code. Null is commonly used to denote or verify the non-existence of something.


1 Answers

With the ternary operator :

String string = bs != null ? f.format(bs) : "";
like image 177
gontard Avatar answered Sep 25 '22 08:09

gontard