0

I have writen a code like this:

    String name="";
    String path="hai";
    if(path.contains(name))
    {
        System.out.println("its working"+name.length());
    }

Output: its working0

I couldn't understand how the if condition satisfies .please help

1
  • 1
    It's not much of a question. An empty string is a substring of the string (here). I guess you're asking why, but the answer to that is: because that's how contains works. (And from a set perspective it makes sense, with the empty string being the empty set). Commented Sep 28, 2014 at 17:52

4 Answers 4

1

All non-null strings contain the empty string "".

In your code, the if at the moment it is executed, is, actually:

if ("hai".contains(""))

The expression inside the if yields true, satisfying it.

About the output, once again, it is like:

System.out.println("its working" + "".length());

Thus printing its working0.

Sign up to request clarification or add additional context in comments.

Comments

0

You are testing if path contains the empty string, but every string (even the empty string) matches this condition so the test always passes.

2 Comments

The title of the post says otherwise
Dici could you please for the above example which i modified
0

The answer is correct. The empty string "" is a substring of any String. Just like the empty set is a subset of any set.

If you evaluate "name".substring(0,0) you get "". Therefore, "" is a substring of "name".

Comments

0

The contains method uses indexOf method internally. If you will look deeper in the source code then you will find a fragment like

if (targetCount == 0) {
    return fromIndex;
}

where targetCount is the length of the target string (empty string in your case) and as you can see that if the length of the target string is 0 then the method returns fromIndex, which has the value 0. The contains return true because 0 > -1, the body of contains method looks like this

indexOf(s.toString()) > -1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.