Search code examples
javaobjectcomparerefer

Comparing Objects which refer to each other in Java


int i = 0;
int j = i;
System.out.println("initial int: " + j); // 0

Integer ii = new Integer(0);
Integer jj = ii;
System.out.println("initial Integer: " + jj); // 0

String k = new String("s");
String l = k;
System.out.println("initial String: " + l); // "s"

Person person1 = new Person("Furlando"); // from constructor -> publ. instance var. 'name'
Person person2 = person1;
System.out.println("initial Person: " + person2.name); // "Furlando"

/*--------------------*/
System.out.println();
/*--------------------*/

i += 1;
System.out.print("added 1 to int: [" + i);
System.out.println("], and primitive which also \"refers\" to that (has a copy, actually), has a value of: [" + j + "]");

ii += 1;
System.out.print("added 1 to Integer object: [" + ii);
System.out.println("], and object which also refers to that, has a value of: [" + jj + "]");

k += "tring";
System.out.print("added \"s\" to String object: [" + k);
System.out.println("], and object which also refers to that, has a value of: [" + l + "]");

person1.name = "Kitty";
System.out.print("changed instance variable in Person object to: [" + person1.name);
System.out.println("], and object which also refers to that, has a value of: [" + person2.name + "]");

/* [COMPILER OUTPUT]
    initial int: 0
    initial Integer: 0
    initial String: s
    initial Person: Furlando

    A) added 1 to int: [1], and primitive which also "refers" to that (has a copy, actually), has a value of: [0]
    B) added 1 to Integer object: [1], and object which also refers to that, has a value of: [0]
    C) added "s" to String object: [string], and object which also refers to that, has a value of: [s]
    D) changed instance variable in Person object to: [Kitty], and object which also refers to that, has a value of: [Kitty]
*/

I understand A, we have a primitive there; no references. By-copy.
I hoped B and C would behave the same way as D - change according to the reference they were given.

Why this object-reference-to-another-object only "works" with user defined objects, not Integers, Strings, etc.?



Thank you all for your answers - now I get it!


Solution

  • String and Integer objects are immutable in Java. When you do: ii += 1 or k += "tring" you create new objects. The variables jj and l points to the old objects. That's why you see different values.