Search code examples
javavariablesinitializationdeclaration

Initializing multiple variables to the same value in Java


I'm looking for a clean and efficient method of declaring multiple variables of the same type and of the same value. Right now I have:

String one = "", two = "", three = "" etc...

But I'm looking for something like:

String one,two,three = ""

Is this something that is possible to do in java? Keeping efficiency in mind.


Solution

  • 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.