Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is String a reference type in Java?

I understand that classes are reference types, for example I created the following class:

class Class {

String s = "Hello";

public void change() {
    s = "Bye";
} }

With the following code, I understand that Class is a reference type:

Class c1 = new Class(); 
Class c2 = c1; //now has the same reference as c1

System.out.println(c1.s); //prints Hello
System.out.println(c2.s); //prints Hello

c2.change(); //changes s to Bye

System.out.println(c1.s); //prints Bye
System.out.println(c2.s); //prints Bye

Now I want to do the same thing with a String, that doesn't work. What am I doing wrong here?:

String s1 = "Hello";
String s2 = s1; //now has the same reference as s1 right?

System.out.println(s1); //prints Hello
System.out.println(s2); //prints Hello

s2 = "Bye"; //now changes s2 (so s1 as well because of the same reference?) to Bye

System.out.println(s1); //prints Hello (why isn't it changed to Bye?)
System.out.println(s2); //prints Bye
like image 892
Robin Avatar asked Jul 22 '18 15:07

Robin


1 Answers

In the first case you are calling a method to the referenced object, thus the referenced object changes, not the 2 references:

method

In the second case you are assigning a new object to the reference itself, which is then pointing to that new object:

new object

like image 157
Loris Securo Avatar answered Oct 21 '22 04:10

Loris Securo