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.
This should work with immutable objects. It doesn't make any sense for mutable objects for example:
All the variables would be pointing to the same instance. Probably what you would need in that case is:
Or better yet use an array or a
Collection
.No, it's not possible in java.
You can do this way .. But try to avoid it.
You can do this:
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.
Works for primitives and immutable classes like
String
, Wrapper classes Character, Byte.For mutable classes
Three references + one object are created. All references point to the same object and your program will misbehave.
You can declare multiple variables, and initialize multiple variables, but not both at the same time:
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".
I do not think that is possible you have to set all the values individualling (like the first example you provided.)
The Second example you gave, will only Initialize the last varuable to "" and not the others.