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:

    String temp = System.getProperty("XYZ");
    String result = "default";
    if(temp != null && !temp.isEmpty()){
        result = temp;
    }

I have made another attemp using a ternary operator:

    String temp;
    String result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";

The isNotNullOrEmpty() Method

 private static boolean isNotNullOrEmpty(String str){
    return (str != null && !str.isEmpty());
}

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

String result = isNotNullOrEmpty(System.getProperty("XYZ")) ? System.getProperty("XYZ") : "default";

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

String result = isNotNullOrEmpty(String temp = System.getProperty("XYZ")) ? temp : "default";

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

Jon Skeet
people
quotationmark

Sounds like you probably want a simple method like this:

public String getValueOrDefault(String value, String defaultValue) {
    return isNotNullOrEmpty(value) ? value : defaultValue;
}

Then:

String result = getValueOrDefault(System.getProperty("XYZ"), "default");

At this point, you don't need temp... you've effectively used the method parameter as a way of initializing the temporary variable.

If you really want temp and you don't want an extra method, you can do it in one statement, but I really wouldn't:

public class Test {
    public static void main(String[] args) {
        String temp, result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
        System.out.println("result: " + result);
        System.out.println("temp: " + temp);
    }

    private static boolean isNotNullOrEmpty(String str) {
        return str != null && !str.isEmpty();
    }
}

people

See more on this question at Stackoverflow