I have two classes using the same String
value, and both storing them as a final private field.
public class Foo{
private final String str;
private final Bar bar; //notice this
public Foo(String in){
this.str=in;
this.bar=new Bar(in); //option 1
this.bar=new Bar(this.str); //option 2
}
}
And here comes Bar
:
public class Bar{
private final String boo;
public Bar(String in){
this.boo=in;
}
}
- Does Java store the same object everywhere, or does it make a copy for each instance*?
- Is your answer the same for both option 1 and 2?
*Intuition hints at the former but you can never be sure with Java.
Side question:
What I'm trying to do is this: Foo
does some processing on str
and uses Bar
as a utility class. Conceptually Foo
and str
are closely linked together, but apart from the constructor, Foo
doesn't touch str
directly again, but only through Bar
.
I thought about removing str
from Foo's fields in fear of Java allocating the same string twice, which prompted this question. But from a software engineering / code correctness standpoint, should I remove it?