george_h george_h - 7 months ago 55
Java Question

Why does contains() method find empty string in non-empty string in Java

This is a weird behavior I found with Java's

methods. If I have a non-empty string says
and I try to look for an empty string inside it, it always returns
whereas I would expect it to return

So basically, why does the code below return true and 0 ?

String testThis = "";
String fileName = "blablablabla";

Logically (at least to me)
does not occur in
says it does, why?

Answer Source

An empty string occurs in every string. Specifically, a contiguous subset of the string must match the empty string. Any empty subset is contiguous and any string has an empty string as such a subset.

Returns true if and only if this string contains the specified sequence of char values.

An empty set of char values exists in any string, at the beginning, end, and between characters. Out of anything, you can extract nothing. From a physical piece of string/yarn I can say that a zero-length portion exists within it.

If contains returns true there is a possible substring( invocation to get the string to find. "aaa".substring(1,1) should return "", but don't quote me on that as I don't have an IDE at the moment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download