Skip to content
Advertisement

Java – Check Not Null/Empty else assign default value

I am trying to simplify the following code.

The basic steps that the code should carry out are as follows:

  1. Assign String a default value
  2. Run a method
  3. If the method returns a null/empty string leave the String as default
  4. If the method returns a valid string set the String to this result

A Simple example would be:

JavaScript

I have made another attemp using a ternary operator:

JavaScript

The isNotNullOrEmpty() Method

JavaScript

Is it possible to do all of this in-line? I know I could do something like this:

JavaScript

But I am calling the same method twice. I would be something like to do something like this (which doesn’t work):

JavaScript

I would like to initialize the ‘temp’ String within the same line. Is this possible? Or what should I be doing?

Thank you for your suggestions.

Tim

Advertisement

Answer

If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement