-3
    public class Example{  
         public static void main(String args[]){  
               String s1=new String("name");
               String s2="name";
               System.out.println(s1==s2);  
    }}  

Why does the above code return false? When a new string "name" is created it's created in the string constant pool as well as the heap. Next when the other string is created using the literal "name", should it not refer to the same object created int heap, as the literal "name" already exist in String Constant Pool?

2 Answers2

2

new always creates a new instance... thus circumventing all caching and pooling. So new String("name") will create a new string object containing the string "name".

The string "name", however is already generated and placed in the pool when the literal "name" is found. Thus even before new is called.

For the same reason you should always do:

Long.valueOf(42L);

instead of

new Long(42L);

Because new is guaranteed to return a new instance. There is no way around that.

Michaela Elschner
  • 1,268
  • 1
  • 10
  • 22
  • in the question, the `new String` occurs first. Why isn't the String created there used in the next life? – bradimus Sep 05 '16 at 13:53
  • 2
    @bradimus It is not created first... Because before the creation of new String(...) already the literal has been created. – Michaela Elschner Sep 05 '16 at 13:54
  • 1
    Because first it occures in `"name"` inside `new String("name")`. Or if you want seriouse answer strings that will be in constant pool is determined at compail time. – talex Sep 05 '16 at 13:54
  • 1
    Good. Now that we have established that, add it to your answer. – bradimus Sep 05 '16 at 13:56
1

In Java, when you say new, you are guaranteed to get a new object. The instance behind the literal "name" is in the constant pool and it's accessed by the constructor, copied, and returned from your new expression.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436