# Check if a string contains a substring in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jan 8, 2020, updated Aug 5, 2020. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-string-contains-substring

> Learn about six different ways to check if a specific string contains a substring in Java.

One of the most common tasks in Java or any other programming language is to check whether a string contains another string or not. Java provides **multiple ways** to accomplish this task. You can use `contains()`, `indexOf()`, `lastIndexOf()`, `startsWith()`, and `endsWith()` methods to check if one string contains, starts or ends with another string in Java or not.

In this article, you'll **learn about six different ways of checking if a string contains a substring** in Java. Let us start with the first commonly used method &mdash; `contains()`.

## 1. `String.contains()` Method

The first and most popular method used in Java for checking if a string contains another string is `contains()` from the `String` class. This method returns a boolean value based on whether the substring exists in the *this* string or not. 

The `contains()` method searches the substring across the original string and returns `true` if and only if *this* string contains the specified sequence of character values, and `false` otherwise. Here is an example:

```java
String str = "Java is a server-side programming language.";
str.contains("Java"); // true
str.contains("Node.js"); // false
```

It is important to remember that the `contains()` method is **case-sensitive** which means it treats uppercase and lowercase characters differently as shown in the below example:

```java
"Hey, there!".contains("There"); // false
"Java 101".contains("java"); // false
```

For a **case-insensitive** search, you should **convert both string and substring to lowercase** as shown below:

```java
String str = "My name is Atta!";
// case-insensitive search
str.toLowerCase().contains("ATTA".toLowerCase()); // true
```

Since `contains()` returns a boolean value, it means that you can **use it directly in *if* statements** as shown below:

```java
String str = "My name is Atta!";
if(str.contains("Atta")) {
    System.out.println("Hey Atta ?");
} else {
    System.out.println("Hey!");
}

// Hey Atta ?
```

The `contains()` method throws a `NullPointerException` if the given substring is `null`. Another interesting thing to note is that `contains()` **internally calls the `indexOf()` method** (explains below) to check if the given sequence of character exists or not.

## 2. `String.indexOf()` Method

The `indexOf()` method is different than the `contains()` method in a way that it doesn't return a boolean value. Instead, this method **returns the index of the first occurrence of the substring**. If the string does not contain the given substring, it simply returns `-1`.

Ideally, you should use the `indexOf()` method to** find the index of a character** in a string. But it can also be used for substrings matching. Since `contains()` is implemented using the `indexOf()` method, they are essentially the same. It doesn't make any impact on the performance whichever method you use except that the former is more readable than the latter.  
 
Her is an example that shows how to use the `indexOf()` method in Java:

```java
String str = "Apple, Orange, & Mango are Fruits.";
str.indexOf("Apple"); // 0 (true)
str.indexOf("Mango"); // 17 (true)
str.indexOf("Banana"); // -1 (false)
```

Similar to `contains()`, the `indexOf()` method is also **case-sensitive** which means that you have to convert both strings to lowercase before performing a case-insensitive search as shown below:

```java
String str = "iPhone X";
str.indexOf("x"); // -1 (false)
str.toLowerCase().indexOf("I".toLowerCase()); // 0 (true)
```

## 3. `String.lastIndexOf()` Method

The `lastIndexOf()` method is similar to `indexOf()` except that it returns the index of the last occurrence of the substring. It starts the search from the tail and returns `-1` if substring not found in the string or the last position of the substring.

Here is an example that demonstrates how you can use the `lastIndexOf()` method to check if a string contains another substring:

```java
String str = "iPhone X, iPhone XL";
str.lastIndexOf("iPhone"); // 10 (true)
str.lastIndexOf("Apple"); // -1 (false)
```

## 4. `String.startsWith()` Method

The `startsWith()` method can also be used for a more specific use-case where you want to check if a string starts with a given substring. This method returns a boolean value `true` if *this* string begins with the specified string, otherwise `false`.

The following example shows how you can use the `startsWith()` method to check if a string starts with the specified prefix string:

```java
String str = "Java 101";
str.startsWith("Java"); // true
str.startsWith("101"); // false
```

Just like the other `String` class methods we have discussed above, `startsWith()` is also case-sensitive. So you have to lowercase both strings to perform a case-insensitive search as shown below:

```java
String str = "Java 101";
str.startsWith("java"); // false
str.toLowerCase().startsWith("java".toLowerCase()); // true
```

## 5. `String.endsWith()` Method

As the name suggests, the `endsWith()` method is an opposite of `startsWith()` that returns `true` if and only if the string ends with a specified suffix string, and `false` otherwise. Here is an example:

```java
String str = "Spring Boot & MySql";
str.endsWith("MySql"); // true
str.endsWith("Boot"); // false
```

`endsWith()` is also **case-sensitive** which means you need to convert both string and substring to lowercase of case-insensitive search:

```java
String str = "Spring Boot & MySql";
str.endsWith("mysql"); // false
str.toLowerCase().endsWith("mysql".toLowerCase()); // true
```

## 6. `String.matches()` Method

Finally, let us look at another way of checking if a string contains a given substring by using the `matches()` method from the `String` class. Unlike other methods we discussed above, `matches()` accepts a [regular expression](https://attacomsian.com/blog/javascript-regular-expressions) as a parameter and searches the string for a match. If it finds the matches, it returns `true`, and `false` if no match is found.

Here is an example that demonstrates how you can use the `matches()` method to check if a string contains another substring or not:

```java
String str = "MEAN Stack stands for MongoDB, Express, Angular, and Node";

// start with
str.matches("(?i)mean.*"); // true

// ends with
str.matches("(?i).*node"); // true

// anywhere
str.matches("(?i).*mongo.*"); // true
```

[Here](https://www.vogella.com/tutorials/JavaRegularExpressions/article.html) is a good article to learn more about regular expression in Java.

## Conclusion

That's all folks. In this article, we have discussed various ways to check if a string contains another string in Java. You can use any of the methods above depending on your needs.

It is recommended to use `indexOf()` or `lastIndexOf()` methods only if you need the index of substring. Otherwise `contains()` is more readable and returns a boolean value which can be used in *if* statements directly.
