Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare multiple String variables and initialize them to all to null at once

Tags:

java

I want to declare all of them null. Am I doing someting wrong or is this the right method?

String a = null, b = null, c = null, d = null;

(Is there any more compact syntax for doing this?)

like image 302
asda Avatar asked Jun 28 '11 11:06

asda


People also ask

Can you initialize multiple variables at once?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

How do you declare and initialize multiple variables in Java?

Declaring and Assigning Variablesint a, b, c; You can also assign multiple variables to one value: a = b = c = 5; This code will set c to 5 and then set b to the value of c and finally a to the value of b .

Can you declare and initialize multiple variables with a single expression?

You can declare several variables in one declaration statement, specifying the variable name for each one, and following each array name with parentheses. Multiple variables are separated by commas.

Can you initialize multiple variables at once Java?

In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.


1 Answers

Yep. That's the way to do it.

You could also do

String a, b, c, d;
a = b = c = d = null;

The line below however won't compile:

String a = b = c = d = null;  // illegal

(Note that if these are member variables, they will be initialized to null automatically.)

like image 92
aioobe Avatar answered Oct 21 '22 15:10

aioobe