0

Replace will create new object and both side this new will be compared. then why it showing false.

When exactly created new string will be added in string pool?

if("String".replace("g", "G") == "String".replace("g", "G"))
{
    System.out.println("True");    
} else {
    System.out.println("False"); 
}
Bram
  • 2,515
  • 6
  • 36
  • 58
Piyush Aghera
  • 965
  • 7
  • 13
  • I thought of marking it as duplicate :).. Not sure whether we have an *exact* duplicate here. I think the OP wants to know whether the `replace` operation gives same string from constants pool or creates a new one – TheLostMind Apr 16 '15 at 06:13

1 Answers1

7

because replace() will always return a new String instance. So the 2 same calls to replace method will return 2 different instances with same value.

  1. use equals() instead of == if you want to compare value
  2. Use intern() on both replaced values if you want to add the string to the string constants pool (and are bent on using == :P)

    if ("String".replace("g", "G").intern() == "String".replace("g", "G").intern()) {
        System.out.println("True");
    } else {
        System.out.println("False");
    }
    

    }

OP :

true
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Where is it created ? , In Heap or String pool ? I need to used equal only if they are in heap. If they are in string pool then == should work. – Piyush Aghera Apr 16 '15 at 06:09
  • 2
    @PiyushAghera - always remember --> Only *interned* strings and *String literals* go into the String constants pool. All other strings created from operations like `replace()`, `substring()` etc go into the `heap`. It is worth noting that *The String constants pool* is part of the *heap* :) – TheLostMind Apr 16 '15 at 06:12
  • 2
    @PiyushAghera "If they are in string pool then == should work" which proves that instance created and returned by `replace` is not interned and doesn't come from string pool. – Pshemo Apr 16 '15 at 06:16