permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Sring compare 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 "Sring compare" Watch "Sring compare" New topic
Author

Sring compare

Raghu Raj Reddy
Greenhorn

Joined: Oct 18, 2005
Posts: 2
1)if("String".substring(0) == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");
2)if("String".replace('g','G') == "StrinG")
System.out.println("Equal");
else
System.out.println("Not Equal");

in #1 substring create new String and return ,and compare with "String"
so it is giving Equal
in #2 replace create new String "StrinG" and compare with "StrinG"
then it should also give Equal but it is giving NotEqual

please explain me .in doc also they said that both are construct new string...
vidya sagar
Ranch Hand

Joined: Mar 02, 2005
Posts: 580

if("String".substring(0) == "String")


Condition returns true because in substring method, when 0 is passed as argument it returns the same string(because result of substring method is going to be same as main string("String"))

Similary
if("String".replace('g','g') == "String") --returns true

--> because both old string and new string are same, so same string is returned
and result is true

but here

if("String".replace('g','G') == "StrinG")


Lowercase 'g' differs from upper case 'G' , so method returns strinG (at runtime) which
have different reference from "strinG"(in the right side)

note: == checks for references

Hope u get it
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Sring compare