startsWith() method in Java returns true on an empty String. How?
java
Solution
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.
Problem
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?