[Solved] Why this code is not printing 30, since int is primitive and mutable?


Why this code is not printing 30

Because you’re outputting the age field of person2, which you never set to 30. You’re setting the age field of person1 to 30, but not person2. Instance fields are instance-specific.

In particular, if you were expecting this line to create some link between the instances:

person2.setAge(person1.getAge());

it doesn’t. It gets the value of teh age field of person1 and then assigns that value (10, at that point) to the age field of person2. There is no ongoing link between them.

Blow-by-blow account:

Person person1 = new Person();        // Creates a Person instance
person1.setAge(10);                   // Sets person1's age to 10

Person person2 = new Person();        // Creates a separate Person instance
person2.setAge(person1.getAge());     // Sets person2's age to 10

person1.setAge(30);                   // Sets person1's age to 30; no effect on person2

System.out.println(person2.getAge()); // Shows person2's age (10)

…since int is primitive and mutable?

int is primitive; you could argue that it’s not mutable, if you take mutable to mean what it normally means: Having state that can change. ints don’t have that. 5 is 5 is 5 and cannot change. Variables containing int values can be updated to contain different int values, but that’s changing the variable, not the int.

In contrast, objects have state that can change without changing the variable that refers to them:

// Create a LinkedList and save a reference to it in `list`
List<String> list = new LinkedList<String>();

// Change the state of the list
list.add("Foo");

In the second statement above, the variable list isn’t changed; it still contains a reference to the same list. That statement changes the state of the list (not the state of the variable referring to it).

6

solved Why this code is not printing 30, since int is primitive and mutable?