diaco diaco - 29 days ago 4
Java Question

Different types, but same reference

So... Back to the basics of Java. I have somehow forgotten about that crucial fact in Java. I have been running some tests, but have forgotten a crucial fact regarding this example.

class Foo1 {
private String str1;
private String str2;
foo1(String input){
this.str1 = input;
this.str2 = new String(input);
}
}


:

class Foo2 {
private String str1;
private String str2;
foo2(String input){
this.str1 = input;
this.str2 = new String(input);
}
}


:

Foo1 foo1 = new Foo1("hello");
Foo2 foo2 = new Foo2("hello");


Now...
Let's assume there is a getter function retrieves the
str1
and
str2
variables from respective instance.

Is it then in this example correct to state that the two
str1
Strings have the same reference, whereas the two
str2
Strings in each object, do NOT have the same reference?

Answer

Yes.

str1: Assigning two fields to the same object (and it is the same object here, because String literals are all interned) will result in them containing the same reference.

str2: Calling new creates a new object. It will never return a reference to something that already exists.

Comments