+ 1

Question about values and references in Java

Can someone take a look at this code and explain to my whats happening? A get that int is a primitive type and not a Class, so it is understandable that it acts differently, but String is a class right? So whats going on here? public class javaStuff{ public static class Person{ private String name; public Person(String name){ this.name = name; } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } } public static void main(String args[]){ // changing b DOES NOT change a int aInt = 10; int bInt = aInt; bInt++; System.out.println(aInt + " " + bInt); // changing b DOES NOT change a String aString = "ten"; String bString = aString; bString += "_eleven"; System.out.println(aString + " " + bString); // changing b DOES change a Person aPerson = new Person("Joe"); Person bPerson = aPerson; bPerson.setName("FatJoe"); System.out.println(aPerson.getName() + " " + bPerson.getName()); } } Changing "bInt" does not affect "aInt" and the same is true for "bString" and "aString", but in the case of the Person class it works differently. Whats up with that?

12th Jan 2017, 9:44 AM
harsandor
2 Answers
+ 1
Even if String is a class don't forget that String is immutable. Every time you change the value of bString you change the reference of it. So to me it's normal that String and Person don't do the same thing.
12th Jan 2017, 9:52 AM
Florian Castelain
Florian Castelain - avatar
0
public class javaStuff{ public static class Person{ private String name; Person(String name){ this.name = name; } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } } public static void main(String args[]){ // changing b DOES NOT change a int aInt = 10; int bInt = aInt; bInt++; System.out.println(aInt + " " + bInt); // changing b DOES NOT change a String aString = "ten"; String bString = aString; bString += "_eleven"; System.out.println(aString + " " + bString); // changing b DOES change a Person aPerson = new Person("Joe"); Person bPerson = new Person(aPerson.getName()); bPerson.setName("FatJoe"); System.out.println(aPerson.getName() + " " + bPerson.getName()); } }
12th Jan 2017, 10:51 AM
ASNM
ASNM - avatar