Initializing multiple variables to the same value in Java

418,450

Solution 1

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.

Solution 2

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

Solution 3

No, it's not possible in java.

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

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

Solution 4

Works for primitives and immutable classes like String, Wrapper classes Character, Byte.

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

For mutable classes

Reference r1 = Reference r2 = Reference r3 = new Object();`  

Three references + one object are created. All references point to the same object and your program will misbehave.

Solution 5

You can do this:

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

But these will all point to the same instance. It won't cause problems with final variables or primitive types. This way, you can do everything in one line.

Share:
418,450

Related videos on Youtube

user83643
Author by

user83643

Updated on March 27, 2021

Comments

  • user83643
    user83643 about 3 years

    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.

    • khachik
      khachik almost 13 years
      Keep efficiency in mind efficiency of what?
    • user83643
      user83643 almost 13 years
      Length of code, time to type, visually simple. That's what I mean. I know that reserving memory is reserving memory and that this question is related to the 'human' side of things.
    • Simeon
      Simeon almost 13 years
      I'd say that this is generally against accepted Java conventions, it will surprise the reader and IMHO is harder to read than declaring them on separate lines.
    • Amit Kumar Gupta
      Amit Kumar Gupta almost 9 years
      I checked for the performance (on java 8) a = b =c = d =e = true takes 2x+ times than a = true; b = true ; and so on.
    • Adam Gent
      Adam Gent almost 3 years
      @AmitKumarGupta I tested it on JDK16 and I found no discernible difference using JMH. How did you test? Also once you assign one,two,three something other than a constant it becomes the same (multiple assignment). In fact multiple variable assignment can be leveraged when dealing with multithreaded code since DUP uses the stack.
  • Brian Roach
    Brian Roach almost 13 years
    +1 for pointing out that what he's trying to do isn't the norm.
  • bcorso
    bcorso over 10 years
    There are cases where this makes sense for mutable objects as well. For instance, in the constructor of linkedlist implementation where initially: head = tail = new Node(value). So both head and tail should point to the same reference.
  • Ranjit
    Ranjit over 10 years
    this is for String, but how for integers ?? int day, month, year, hour, min = day = month = year = hour = 0; is it right ??
  • GKFX
    GKFX almost 10 years
    I disagree with "All references pointing to same object and your program will misbehave." The only problem is that what happens to the object of one reference happens to the object of another reference -- because it's the same object. This isn't misbehaviour; it's how Java works.
  • Aequitas
    Aequitas over 8 years
    Are these the same object? If I later do one = "cat" will two.equals("cat") return true?
  • IgorGanapolsky
    IgorGanapolsky over 8 years
    The only caveat is that this wouldn't work for static variables.
  • IgorGanapolsky
    IgorGanapolsky over 6 years
    What about integer declarations?
  • TheCrazyProfessor
    TheCrazyProfessor over 6 years
    Why does this not work with Calendar? if you do that every variable behave like its the same when you manipulate one of them
  • Neuron
    Neuron about 6 years
    what do you mean with "misbehave"? It will behave differently then 3 separately initialised objects, but it really depends on what you want..
  • Neuron
    Neuron about 6 years
    Can you explain why this should be avoided?
  • Yuhang Lin
    Yuhang Lin over 5 years
    @Lonely Neuron I think it's easy to make a mistake if you use it in this way.
  • Neuron
    Neuron over 5 years
    @YuhangLin i was just hoping for a better answer
  • Alexander Heim
    Alexander Heim over 5 years
    @LonelyNeuron Well for one it´s slower. It takes almost twice the time as if you would just initialize seperately. One the other this "feature" is unnecessary. I can´t think of a scenario that wouldn´t be solvable by using a different approach. It´s simply said not a clean code.
  • Neuron
    Neuron over 5 years
    @AlexanderHeim Thanks for the explanation. But the reason I asked was because it should be part of the answer.
  • Cristian Gutu
    Cristian Gutu about 4 years
    @AlexanderHeim why is it slower?
  • starscream_disco_party
    starscream_disco_party about 3 years
    @Zeeen try it in your Groovy interpreter!
  • Zeeen
    Zeeen about 3 years
    That is groovy, not plain old Java. also it doesn't work on regular java, I just tested it.
  • starscream_disco_party
    starscream_disco_party about 3 years
    ah yeah look at that, must have gotten some tabs mixed up when i submitted this answer. at least it looks like it helped some other confused person ¯\_(ツ)_/¯