0

I'm newbie to java.

class Demo{
    public static void main(String[] args) {
        String s1=new String("abc"); 
        String s2=new String("abc"); 
        String s3="xyz";
        String s4="xyz";

        System.out.println(s1==s2); //line 7
        System.out.println(s3==s4); //line 8
    }
}

I just don't understand why line 7 got false and line 8 got true.

I would be so grateful if someone explain me this.

  • 2
    Related: stackoverflow.com/questions/2486191/what-is-the-java-string-pool-and-how-is-s-different-from-new-strings – tonychow0929 Jul 04 '15 at 01:48

1 Answers1

-1

When you use:

String s1=new String("abc"); 
String s2=new String("abc"); 

s1 and s2 are to different objects both created at runtime.

String s3="xyz";
String s4="xyz";

s3 and s4 are assigned at compilation time and java compiler stores only one copy of the string.

Java intern

Rodolfo
  • 1,091
  • 3
  • 13
  • 35