Initializing multiple variables to the same value in Java Initializing multiple variables to the same value in Java java java

Initializing multiple variables to the same value in Java


String one, two, three;one = two = three = "";

This should work with immutable objects. It doesn't make any sense for mutable objects for example:

Person firstPerson, secondPerson, thirdPerson;firstPerson = secondPerson = thirdPerson = new Person();

All the variables would be pointing to the same instance. Probably what you would need in that case is:

Person firstPerson = new Person();Person secondPerson = new Person();Person thirdPerson = new Person();

Or better yet use an array or a Collection.


You can declare multiple variables, and initialize multiple variables, but not both at the same time:

 String one,two,three; one = two = three = "";

However, this kind of thing (especially the multiple assignments) would be frowned upon by most Java developers, who would consider it the opposite of "visually simple".


No, it's not possible in java.

You can do this way .. But try to avoid it.

String one, two, three;one = two = three = "";