3

Possible Duplicate:
Why does “abcd”.StartsWith(“”) return true?

The following simple Java code just uses the startsWith() method.

package startwithdemo;

final public class Main
{    
    public static void main(String[] args)
    {
        System.out.println("My String".startsWith("M"));
        System.out.println("My String".startsWith("My"));
        System.out.println("My String".startsWith(""));
    }
}

It displays true in all the cases. The first two cases are obvious but in the last case (with an empty String), it's returning true. How?

Community
  • 1
  • 1
Lion
  • 18,729
  • 22
  • 80
  • 110
  • Please check this topic: http://stackoverflow.com/questions/3872936/why-do-strings-start-with-a-in-java – Ata S. Apr 12 '12 at 21:21
  • 2
    No characters? Makes sense to me, all strings start with nothing, then add characters. – Dave Newton Apr 12 '12 at 21:21
  • ...Because that's the defined behavior of the function? http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#startsWith%28java.lang.String%29 – VeeArr Apr 12 '12 at 21:21

4 Answers4

10

Because that's how the API was designed, see the javadoc.

But more seriously, one analogy can be to look at sets. Let's imagine a string is a set of characters, then the empty string is the empty set. In set theory, the empty set is always part of any set.


Why is the empty set a subset of every set? (taken from here)

The set A is a subset of the set B if and only if every element of A is also an element of B. If A is the empty set then A has no elements and so all of its elements (there are none) belong to B no matter what set B we are dealing with. That is, the empty set is a subset of every set.

Another way of understanding it is to look at intersections. The intersection of two sets is a subset of each of the original sets. So if {} is the empty set and A is any set then {} intersect A is {} which means {} is a subset of A and {} is a subset of {}.

You can prove it by contradiction. Let's say that you have the empty set {} and a set A. Based on the definition, {} is a subset of A unless there is some element in {} that is not in A. So if {} is not a subset of A then there is an element in {}. But {} has no elements and hence this is a contradiction, so the set {} must be a subset of A.

JRL
  • 76,767
  • 18
  • 98
  • 146
3

From the Javadoc:

Returns: 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.

Dmitry B.
  • 9,107
  • 3
  • 43
  • 64
2

It is true:

("" + "My String") obviously starts with "".

That's the same as saying "My String" starts with ""

Paul
  • 139,544
  • 27
  • 275
  • 264
1
System.out.println(""+""+""+"string"=="string") // output is true;
Baz1nga
  • 15,485
  • 3
  • 35
  • 61