Reputation: 333
Some months ago, I remember being in an interview and being asked for three different ways to compare strings in Java for their values. Out of curiosity, I'm going to ask it here for my own reference. I thought of two:
str1.equals(str2)
or using compareTo
, both counting as one in totalAny idea? "==", equalsTo, compareTo, and any variations of them are not it I was told.
Edit: Fixed question a bit.
Upvotes: 3
Views: 1615
Reputation: 234847
I can think of a few of ways besides looking at each character yourself or using equals()
or compareTo()
:
s1.startsWith(s2) && s2.startsWith(s1)
s1.contains(s2) && s2.contains(s1)
s1.indexOf(s2) == 0 && s2.indexOf(s1) == 0
Arrays.equals(s1.toCharArray(), s2.toCharArray())
s1.intern() == s2.intern()
To be frank, though, I don't really see the value of this as an interview question. (If the interviewer had the last one in mind, a better question in my opinion would be to identify all the cases when it was safe to use ==
to compare string values.)
Upvotes: 2
Reputation: 53535
Since there was such a huge objection to using ==
I couldn't resist the temptation of posting an answer that does use it (and which is perfectly valid!) :)))
String s1 = new String("abc"); // create string object 1
String s2 = new String("abc"); // create a different string object 2
s1 = s1.intern();
s2 = s2.intern();
System.out.println(s1 == s2); // true!
So if we make sure to intern the strings we can count on ==
.
Other than that, as I suggested in the comments above: it sounds like the interviewer was looking for a "wiseass" solution, for example:
s1.contains(s2) && s2.contains(s1)
or
s1.matches(s2) && s2.matches(s1)
or
s1.replace(s2, "").isEmpty() && s2.replace(s1, "").isEmpty()
and etc.
Upvotes: 4
Reputation: 36513
If I eliminate the ones that take into account casing, there are still plenty of ways, and I'm sure I'm missing some:
s1.equals(s2)
s1.compareTo(s2)
s1.contentEquals(s2)
Objects.equals(s1, s2)
Objects.deepEquals(s1, s2)
EDIT
Technically, this is also a way, but I think it's bad practice:
s1.intern() == s2.intern()
Upvotes: 1
Reputation: 11173
Some other options may be (look here for details)-
1. String comparison using equals
method
2. String comparison using equalsIgnoreCase
method
3. String comparison using compareTo
method
4. String comparison using compareToIgnoreCase
method
Upvotes: 0
Reputation: 3600
I am guessing
1) using '==' operator' which compare strings reference
2) equals() method of String which compare exact string content
3) equalsIgnoreCase() method which compare string content in case incensitive manner
Upvotes: 1