Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

String == and equals() doubt  RSS feed

Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I thought it would output false true.But it gave true

(i==j)---------I and j are references having same value but different object references.Then how come it will produce true.Please explain it for me.
Ranch Hand
Posts: 1156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem isn't with your understanding of == and equals(); it's a question of what you're printing out.

So let's say i and j are two different objects. That means that the condition in your first if would be false. Therefore you print the boolean value of i!=j, as opposed to the String "i!=j". Since i is NOT == j, the expression i!=j is true. That's what gets printed: "true".

You can collapse that first if/else with its two println() statements into just a single...

You have a similar problem with the second if. Let's say i="Ryan" and j="Shiva". The expression in the if will be false, so it goes to the else part. There it prints out the value of the expression !i.equals(j). Since i.equals(j) is false, NOT i.equals(j) is true. So "true" gets printed.

Just replace that whole if/then with...

[ March 29, 2006: Message edited by: Ryan McGuire ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!