File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== operator

 
soujanya Bugatha
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if("String".replace('g','G') == "String".replace('g','G'))
System.out.println("Equal");
else
System.out.println("Not Equal");

can anyone explain me this code?
 
William P O'Sullivan
Ranch Hand
Posts: 859
Chrome IBM DB2 Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Explain the answer or what it is doing?

Have you run this?

If so, what output do you get?

WP
 
ujjawal rohra
Ranch Hand
Posts: 105
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Soujanya

The code snippet does an if check. The left hand condition replaces the 'g' character in "String" with 'G'. The right hand side of this check also does the same resulting into the condition

But the "==" check returns false hence "Not Equal" is printed since the "==" operator checks references(that is another topic ).
PS: If you use .equals then it will print "Equal".

Hope that helped.
 
soujanya Bugatha
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you ujjawal
 
Kevin Florish
Ranch Hand
Posts: 181
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to expand on the answer of ujjawal:

The reason 'Not equals' is returned is because the == relational operator is comparing two reference variables of type String which means for the comparison to be equal both would have to refer to the same object.

If you compare two primitives with == then it compares the actual values held.

The String .equals() method will return true because it overrides the .equals() method of object which uses == on object comparison.

 
Zhenyi Luo
Ranch Hand
Posts: 33
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just be careful, if you replace the code as:
if("StringG" =="StringG")
System.out.println("Equal");
else
System.out.println("Not Equal");


The output will be equal, because string constant pool is used.
 
Tarun Mohandas
Ranch Hand
Posts: 33
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the equals() will return true for this only if it is explicitly overriden in this program right? otherwise it too returns false
 
Michael Broom
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The equals() is overriden for the String class. The String is also final IIRC.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic