Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to automatically initialize a variable if null

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.

like image 535
qrikko Avatar asked Sep 28 '15 07:09

qrikko


People also ask

Can you initialize a variable to null?

You should initialize your variables at the top of the class or withing a method if it is a method-local variable. You can initialize to null if you expect to have a setter method called to initialize a reference from another class.

Can we initialize int variable with null in Java?

An int can't be null .

Should I initialize to null or undefined?

What reason is there to use null instead of undefined in JavaScript? Javascript for Web Developers states "When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to null as opposed to anything else.

Does Java initialize variables to zero?

Most of the times, Java wants you to initialize the variable. If Java does initialize for you, it sets the value to 0, or the closest thing to 0 for the appropriate type.


Video Answer


1 Answers

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

Optional.ofNullable(request.getParameter("bar")).orElse("")

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

Optional.fromNullable(request.getParameter("bar")).or("")

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;
}

emptyIfNull(request.getParameter("bar"))
like image 52
Bhashit Parikh Avatar answered Sep 28 '22 08:09

Bhashit Parikh