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.


I think you remember the elvis operator ( ) which was rejected ( ) from project coin.

However, the jakarta commons have nvl-like functions such as Even though these functions are not standard java, they end up in most programs as dependecy of some library.

The problem you have is a common when you design a function with a valid null result: You have to document and handle the special case everywhere. I can pretty much guarantee you that someone will mess this up in maintenance, resulting in spurious null pointer exceptions. That's why i would, in general, recommend designs that don't return null.

Need Your Help

Couldn't save XML file using Server.MapPath

xml asp-classic

I have a simple asp classic program that update the xml files when a user click a checkbox. It worked fine in my development server but when I deployed it in our main server it display an

Making a Pipeline available to any Application


I have a pipeline that I need to reuse. I need to be able to chose this pipeline from any app as I can with the XML or the Passthrough pipelines.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.