This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes == operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "== operator" Watch "== operator" New topic

== operator

soujanya Bugatha

Joined: May 29, 2012
Posts: 10
if("String".replace('g','G') == "String".replace('g','G'))
System.out.println("Not Equal");

can anyone explain me this code?
William P O'Sullivan
Ranch Hand

Joined: Mar 28, 2012
Posts: 859

Explain the answer or what it is doing?

Have you run this?

If so, what output do you get?

ujjawal rohra
Ranch Hand

Joined: Mar 20, 2010
Posts: 105
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

Joined: May 29, 2012
Posts: 10
Thank you ujjawal
Kevin Florish
Ranch Hand

Joined: Jan 06, 2009
Posts: 179
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.

Java5 Tutorials | Java6 Tutorials | HTML/CSS Tutorials | JavaScript and jQuery Tutorials
Zhenyi Luo
Ranch Hand

Joined: Sep 03, 2012
Posts: 33
Just be careful, if you replace the code as:
if("StringG" =="StringG")
System.out.println("Not Equal");

The output will be equal, because string constant pool is used.
Tarun Mohandas
Ranch Hand

Joined: Feb 12, 2013
Posts: 33

the equals() will return true for this only if it is explicitly overriden in this program right? otherwise it too returns false
Michael Broom

Joined: Mar 04, 2013
Posts: 1
The equals() is overriden for the String class. The String is also final IIRC.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: == operator
It's not a secret anymore!