This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 860

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: 175
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.
subject: == operator
Similar Threads
Why are same strings not equal
Doubts in Strings
String Methods
Unable to understand the Output