Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java's String#replace() method work differently with characters and strings?

Tags:

java

string

Why does the following expression evaluate as false

aStr.replace("H", "H") == "Hello"

while this alternate expression evaluates as true?

aStr.replace('H', 'H') == "Hello"
like image 890
Ana Lacerated Avatar asked Feb 20 '23 00:02

Ana Lacerated


1 Answers

Java caches String literal in String pool, so if there is no change in String it would take an immutable instance from pool and so that both refers to same instance in memory and thus == on reference returns true

So to compare String Object you should use equals() method / compareTo() method


Also See

  • What is String pool in Java?
  • Java String.equals versus ==
like image 61
jmj Avatar answered Feb 21 '23 18:02

jmj