0

I know that Strings are immutable. But I have a doubt in below code:

class StringTest {
   String s1 = "Joe";
   String s2 = "Joe";
   System.out.println(s1 == s2);
}

== checks whether both are referred to same memory address or not (if I am not wrong). If so, even the two strings are assigned to two different variables, why the output says both are referred to same memory address.

Ramson
  • 229
  • 4
  • 12

1 Answers1

1

Java uses an intern pool for performance, and so those two variables refer to the same String. You can use new to get a new one, like

class StringTest {
    public static void main(String[] args) {
        String s1 = "Joe";
        String s2 = new String("Joe");
        System.out.println(s1 == s2);
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249