For a string say, String str = "abc"
both str.indexOf("a")
and str.indexOf("")
return 0. Is this behaviour valid?

- 2,183
- 4
- 27
- 56

- 541
- 1
- 6
- 21
-
2possible duplicate of [Java String.indexOf and empty Strings](http://stackoverflow.com/questions/2683466/java-string-indexof-and-empty-strings) – kirbyquerby Jan 02 '15 at 01:35
-
What do you mean with valid? Do you imply there isn't a sequence of 0 characters at the very start of the string? – Robert Jan 02 '15 at 01:45
-
@Robert, My thought was suppose the search pattern is from an external source and let the pattern be "empty string". Now if I try to see the matched part I get first character instead of empty string. – Viswanadh Kumar Reddy Vuggumud Jan 02 '15 at 01:54
-
@ViswanadhKumarReddyVuggumud Oh, but the matched part always equals the pattern. In particular the pattern and the matched part are of the same length. So you always have to check the length of the pattern, it might also be longer than 1 character. – Robert Jan 02 '15 at 01:59
-
@Robert I agree, not that it is serious but my point is it would make have made much better sense if the other way of finding the matching part is also true :) – Viswanadh Kumar Reddy Vuggumud Jan 02 '15 at 02:08
-
I'm sorry, what other way are you referring to? You can't simply extract 1 character at the found index and then say that it's the matched part. There is nothing special about 1, you have chosen it arbitrarily. What would you suggest `str.indexOf("")` to return instead? Returning `-1` would suggest that it's not part of the string. Returning `str.length()` wouldn't help you to extract an empty string of length 1 either. :) – Robert Jan 02 '15 at 03:17
5 Answers
If only there was some place where they document behaviour of methods.
indexOf(string)
Returns the index within this string of the first occurrence of the specified substring. The returned index is the smallest value k for which:
this.startsWith(str, k)
startsWith(string)
true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object as determined by the equals(Object) method.

- 43,651
- 22
- 107
- 170
Yes. The conceptual reason is pretty similar as adding 0 in math. So ""+"a"+"bc" = "abc" = ""+"a"+"b"+""+"c"
.

- 2,183
- 4
- 27
- 56
The return value of String.indexof("")
is 0, or the starting index, when you pass in an empty string because the empty string ""
is indeed located there.
Think of "abc" as ""
+ "abc"
.
Otherwise, please refer to this documentation:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)
indexOf "returns:the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur."
Therefore, str.indexOf("a") returns 0.

- 3,317
- 6
- 26
- 52