• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Does using == to compare Strings always return true if the Strings are equal?

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
e.g.



is isEqual always true, even though we are creating separate equals objects? Is it to do with how the JVM uses the String literal pool?
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The == is correct in this case because of the String literal pool. The equals method must be used to compare Strings (or any other references). == returns true it two references point to the same object (not necessarily meaningfully equal)...
 
Edward Seager
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your responses. But this case shows that == can be used to compare Strings. Is there a case where == does not work for comparing Strings?
 
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Edward Seager wrote:Thanks for your responses. But this case shows that == can be used to compare Strings. Is there a case where == does not work for comparing Strings?



Yes, this is the case:





Since when you use the "new String("string")" constructor, the JVM creates a new object and does not use the string pool.
 
Sheriff
Posts: 67748
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bottom line:
  • Always use .equals() to check for equality
  • Use == to check for identity
  •  
    Ranch Hand
    Posts: 187
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    thanks i made changes and the code is working well....
    reply
      Bookmark Topic Watch Topic
    • New Topic