Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion about the results of java String

class Test{
       public static void main(String s[]){
              String s1="welcome",s2="come";        
              System.out.println(s1==("wel"+"come"));    //prints : true
              System.out.println(s1==("wel"+s2));        //prints : false
      }
}

I want to know why both the println methods are giving different results. Please explain in details.

like image 429
Chandra Sekhar Nayak Avatar asked Jan 20 '23 06:01

Chandra Sekhar Nayak


2 Answers

== always compares the references themselves.

In the first comparison, the constant string expression "wel" + "come" is evaluated at compile-time, and so you end up with the same interned reference as for the literal used to initialize s1.

In the second case, the concatenation is performed at execution time, creating a new string.

To compare two strings for equality of contents (rather than checking whether two references refer to the same object) use equals:

System.out.println(s1.equals("wel" + "come"));
System.out.println(s1.equals("wel" + s2));
like image 159
Jon Skeet Avatar answered Jan 30 '23 12:01

Jon Skeet


String s1="welcome",s2="come";        
System.out.println(s1==("wel"+"come"));    //prints : true

These are compile-time constants, so the compiler can inline the code to

System.out.println(s1==("welcome"));    //prints : true

Here, the second part is not a compile-time constant, so the compiler can't optimize, hence a new String object is created at runtime:

System.out.println(s1==("wel"+s2));        //prints : false
like image 27
Sean Patrick Floyd Avatar answered Jan 30 '23 14:01

Sean Patrick Floyd