Java String contains()

Learn to check if a string contains the specified substring in Java using the String.contains() API.

1. String.contains() API

The String.contains(substring) searches a specified substring in the current string. It returns true if and only if the substring is found in the given string otherwise returns false.

Please remember that this method searches in a case-sensitive manner.

Assertions.assertTrue("Hello World, Java!".contains("World"));  //searches the whole string

Assertions.assertFalse("Hello World, Java!".contains("world"));  //case-sensitive

The contains() internally uses indexOf() to check the index of the substring. If the substring is found then the index will always be greater than '0'.

2. Null is Not Supported

The String.contains() method does not accept ‘null’ argument and throws NullPointerException.

Assertions.assertThrows(NullPointerException.class, () -> {
  "Hello World, Java!".contains(null);
});

3. Regex Not Supported

The argument should be a literal string. If a regular expression is passed as an argument, it is still considered a string literal.

In the following program, we check for the empty space in the string using the regex ‘//s‘ but the result is false.

Assertions.assertFalse("Hello World, Java!".contains("\\s"));

Happy Learning !!

References: String Java Doc

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.