Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sring compare

 
Raghu Raj Reddy
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic