jQuery in Action, 3rd edition
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Sring compare" Watch "Sring compare" New topic

Sring compare

Raghu Raj Reddy

Joined: Oct 18, 2005
Posts: 2
1)if("String".substring(0) == "String")
System.out.println("Not Equal");
2)if("String".replace('g','G') == "StrinG")
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"))

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
I agree. Here's the link: http://aspose.com/file-tools
subject: Sring compare
It's not a secret anymore!