• Post Reply Bookmark Topic Watch Topic
  • New Topic

== and equals  RSS feed

 
keerthi vineela
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

I am newbiee to this forum.

Can anyone provide me an example when == becomes true then equals() return false with strings.Is it possible(== true and equals() false)?

Thanks in advance,
Keerthi
 
Mansukhdeep Thind
Ranch Hand
Posts: 1163
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the ranch keerthi.

Please search the forum for this question has been asked many times before.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Keerthi. Welcome to the Ranch!

No, that isn't possible*. If == returns true, the two references point at the same Strings, so equals() will always be true.

What is possible is that equals() will return true and == gives false, if you have two separate Strings with the same value. This is why you should never use == to compare Strings. We've got an FAQ explaining more - see AvoidTheEqualityOperator


* It is technically possible, with your own classes, if you do it deliberately and break the equals contract. For example you could override equals() in your class and make it always return false. But just because you can, doesn't mean you should!
 
keerthi vineela
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Matthew..
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!