aspose file tools*
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "== operator" Watch "== operator" New topic
Author

== operator

soujanya Bugatha
Greenhorn

Joined: May 29, 2012
Posts: 10
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

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?

WP
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.


SCJP 6
soujanya Bugatha
Greenhorn

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

Joined: Jan 06, 2009
Posts: 176
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("Equal");
else
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
Greenhorn

Joined: Mar 04, 2013
Posts: 1
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
 
subject: == operator