3

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:

  1. str1.equals(str2) or using compareTo, both counting as one in total
  2. comparing character by character

Any idea? "==", equalsTo, compareTo, and any variations of them are not it I was told.

Edit: Fixed question a bit.

Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40
HikeTakerByRequest
  • 333
  • 1
  • 2
  • 15
  • The answer is "it depends". What are you trying to check in the comparison? if you want to check that both strings have the same "toString()" value you should indeed use `equals`. If you want to check if that's the exact same object (you almost *never* want to do that) you should use `==`. – Nir Alfasi Jul 12 '15 at 02:20
  • You can also use the compare() function, create your own class, or ==: check out [How do I compare strings in Java](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – LinkBerest Jul 12 '15 at 02:21
  • To check if they both have the same value. But three different ways to do it. – HikeTakerByRequest Jul 12 '15 at 02:21
  • Did the question semantic mean "compare characters in strings", or just "compare strings"? – light Jul 12 '15 at 02:21
  • The question was phrased: "List three ways to compare two strings to see if they are the same sentence. (value)" – HikeTakerByRequest Jul 12 '15 at 02:23
  • 1
    Just curious: why is `.equals()` counted as the same as `compareTo()`? – light Jul 12 '15 at 02:23
  • I was told they are close enough. Regardless, the solution was some completely different way of comparison but I can't seem to recall it. – HikeTakerByRequest Jul 12 '15 at 02:29
  • With all the additional edits to this question, I'm betting option 3 was: overriding the standard compare or equals methods in your custom class. – LinkBerest Jul 12 '15 at 02:29
  • No, it wasn't that. This is peculiar, I understand, but there was another solution. – HikeTakerByRequest Jul 12 '15 at 02:32
  • OP here. I think it may have been using `String.valueOf(str1)` and `String.valueOf(str2)`, and then comparing the results by using `==`. Would that work? – HikeTakerByRequest Jul 12 '15 at 02:34
  • 2
    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. – Nir Alfasi Jul 12 '15 at 02:34
  • Perhaps something baroque like `Arrays.equals(s1.toCharArray(), s2.toCharArray())`? – Ted Hopp Jul 12 '15 at 02:35
  • @Manbearpig: `String.valueOf(str1) == String.valueOf(str2)` would **not** be an accurate way of comparing strings. It would suffer from the same problem as simply doing `str1 == str2`. – sstan Jul 12 '15 at 02:41
  • @sstan: All I can remember is that the interviewer used some string method or property or something of each string, and then said that using `==` in the end between these two objects should return true if they have the same value. He said it would not suffer from the same issue as `str1 == str2`. Though, I reiterate, the solution was not `str1 == str2`. – HikeTakerByRequest Jul 12 '15 at 02:43
  • 1
    OK, I'm confused. Was the purpose of the interview to find out how much the interviewee knows, or to show off how much the interviewer knows? – ajb Jul 12 '15 at 02:46
  • If the idea was to use `==` at the end, then it sounds like the interviewer was looking for you to use `intern()`. – Ted Hopp Jul 12 '15 at 02:46
  • @TedHopp: I did not know the point was to use ==. Only later did he have present a solution that used ==, but not using it to directly compare the initial two strings. – HikeTakerByRequest Jul 12 '15 at 02:48

6 Answers6

4

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.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • This may have been the one. Will this always work, whereas `str1 == str2` without the intern wouldn't? – HikeTakerByRequest Jul 12 '15 at 02:46
  • You may be right. If that's the case, the company deserves to hire someone who is highly skilled in obscure tricks and useless knowledge, but can't write a practical program worth ^#&^#@. – ajb Jul 12 '15 at 02:48
  • @Manbearpig indeed. without the intern it might work and might not: if one of the strings was created using the `new` keyword it won't work without intern. – Nir Alfasi Jul 12 '15 at 02:49
  • @ajb thanks for the multiple compliments :) May the rest of your weekend be awesome! – Nir Alfasi Jul 12 '15 at 02:49
  • Plus I should mention that I have *never* used `intern()` in a Java program, nor have I seen it used in any programs I've worked on. So if the employer is basing its hiring decisions on whether the candidates know about a method that has almost no practical use, I shudder to think what the quality of their software must be like. – ajb Jul 12 '15 at 02:50
  • By the way, the first solution is the only one which I don't consider as "smartass" - in order to come up with it you need to have an understanding of how strings (and string-pool) works in Java. It's not about "knowing the string-api" as much as it is about *understanding* how strings work in Java. – Nir Alfasi Jul 12 '15 at 02:51
  • I agree with you both. I, too, have never encountered the usage of `intern()` in Java code, and it did bug me that it was the only technical question I was given, and that I got wrong. Oddly enough, I have an interview with the same company in a couple of weeks. Hopefully it's a little more straightforward this time. Thanks again everyone for the help! – HikeTakerByRequest Jul 12 '15 at 02:52
  • BTW2: it would be a better approach (from the interviewer) had she asked: can you safely use `==` to compare strings if yes: how, and if not - why. But that's just my personal opinion. – Nir Alfasi Jul 12 '15 at 02:53
2

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.)

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

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

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
1

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()
sstan
  • 35,425
  • 6
  • 48
  • 66
0

There are four ways:
==
.equals()
compareTo()
compare()

Read more

Vy Do
  • 46,709
  • 59
  • 215
  • 313
  • == and compareTo don't count as additional I was told. – HikeTakerByRequest Jul 12 '15 at 02:24
  • He asked for "compare Strings" and not its reference. So == is simply wrong, for it compares the reference. –  Jul 12 '15 at 02:33
  • I don't think `==` counts at all. If I'm the interviewer and the candidate suggests `==` as a way to compare `String`s, the interview is over. (OK, that's an exaggeration, but it definitely shows a lack of basic Java knowledge.) – ajb Jul 12 '15 at 02:40
0

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

Razib
  • 10,965
  • 11
  • 53
  • 80