Home » Java » Is there a way to automatically initialize a variable if null

Is there a way to automatically initialize a variable if null

Posted by: admin December 28, 2021 Leave a comment


I have this code in Java:

String foo = request.getParameter("bar");
if (foo == null) { 
    foo = ""; 

There are multiple values checked this way. In other languages I would probably be able to do something like this:

String foo = request.getParameter("bar") || "";

I was really just wondering if there is an equivalent in Java.


If you use java 8, you can probably go with something like this:


If you don’t use java 8, you have the option to use the Optional from Google Guava. Which offers similar API. For ex.


Both of these allow specifying a function to create the alternate value as well.

If you just want to go old-school, create a method like:

static String emptyIfNull(String value) {
    if (value == null) return "";
    else return value;



String foo = request.getParameter("bar") !=null ? request.getParameter("bar") :""; 

or if you feel like getParameter() calling twice, you can write

String foo = request.getParameter("bar");
foo = foo!=null? foo : "";

That’s called ternary operator or conditional operator (:?).


Apache Commons Lang has the method ObjectUtils::defaultIfNull. You could easily implement it on your own using sᴜʀᴇsʜ ᴀᴛᴛᴀ’s approach:

public static <T> T defaultIfNull(T object, T defaultValue) {
    return object == null ? defaultValue : object;


I would suggest to use MoreObjects.firstNonNull from google Guava in order to not call
request.getParameter(“bar”) twice.

String foo = MoreObjects.firstNonNull(request.getParameter("bar"), "");