0

From Core Java for the Impatient:

a variable can only hold a reference to an object ...

and I try it out like this and it seems to work:

public class Person{
    public String m_name;
    public int m_age;

    Person (final String name, final int age){
        m_name = name;
        m_age = age;
    }

    public static void main(String[] args){
        Person a = new Person("John", 45);
        Person b = a;

        System.out.printf("Person a is %s, aged %d\n", a.m_name, a.m_age);
        System.out.printf("Person b is %s, aged %d\n", b.m_name, b.m_age);

        a.m_name = "Bob";

        System.out.printf("Person a is now %s, aged %d\n", a.m_name, a.m_age);
        System.out.printf("Person b is now %s, aged %d\n", b.m_name, b.m_age);
    }
}
/*Output:
Person a is John, aged 45
Person b is John, aged 45
Person a is now Bob, aged 45
Person b is now Bob, aged 45*/

However, it doesn't seem to work for just String objects or primitive types (though, admittedly latter are not objects in the sense of being class instances):

String aS = "John";
String bS = aS;
aS = "Bob";
System.out.println(aS + '\n' + bS);

/*Output:
Bob
John*/

int a = 10;
int b = a; 
a = 5; 
System.out.printf("a = %d, b = %d", a, b);

/*Output:
a = 5, b = 10*/

I'm wondering why this dichotomy? Thanks

ps: Person class attributes public to avoid mutators, accessors for this simple example

shanlodh
  • 1,015
  • 2
  • 11
  • 30
  • 1
    You don't see the difference between `a.something = somethingelse;` and `a = somethingelse;`? – Erwin Bolwidt Jun 27 '18 at 07:12
  • Could you explain what would be the expected behavior? – Oresztesz Jun 27 '18 at 07:17
  • @Erwin Bolwidt: that's the issue - if a is an instance of a user-defined class it will have .something but if a is just a String instance then there are no additional attributes. I think gagan singh reply below is kind-of alluding to this – shanlodh Jun 27 '18 at 07:27
  • There is nothing special about String, it just doesn't have any fields that you can assign to (since they're `private`) - you can easily make a class that works just like `String`. And primitives are not references so they fall outside of this. – Erwin Bolwidt Jun 27 '18 at 08:15

1 Answers1

0

you are not reassigning "a"

a.m_name = "Bob";

try doing this

a = new Person("Bob", 20);

then you will similar behaviour to string example you listed.

gagan singh
  • 1,591
  • 1
  • 7
  • 12