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.
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.
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.
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.
With the ternary operator :
String string = bs != null ? f.format(bs) : "";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With