Is there any situation where
if (str1.contains(str2)) {}
and
if (str1.indexOf(str2)>=0) ) {}
might be different?
A colleague has been changing all occurrences of the 1st form for the 2nd. But I don't see the reason and I can't ask him.
Printable View
Is there any situation where
if (str1.contains(str2)) {}
and
if (str1.indexOf(str2)>=0) ) {}
might be different?
A colleague has been changing all occurrences of the 1st form for the 2nd. But I don't see the reason and I can't ask him.
Firstly welcome to Java Programming Forums
As far as im aware .contains() is a newer method that is just a specialized case of indexOf()
First off, contains returns true/false while indexOf will return the index of the search.
But the magic is in the contains method, you ready for this, its a funny one :)
Code :public boolean contains(CharSequence s) { return indexOf(s.toString()) > -1; }
// Json
Better practice, maybe... But hardly worth the trouble of having to check all those differences that light up in CVS (in my opinion).
Thanks for the replies.
Marcel
The methods have different use, if you need to check if the String contains something then use the contains, but if you want to know where in the String it is contained, use the indexOf method.
// Json