Java – Check if a String contains another String

In Java, we can use String’s .contains() or .indexOf() to check if a String contains another String.

1. String contains()

1.1 Case sensitive.

JavaExample1.java

package com.mkyong.example;

public class JavaExample1 {

    public static void main(String[] args) {

        String name = "mkyong is learning Java 123";

        if (name.contains("Java")) {
            System.out.println("found Java");
        } else {
            System.out.println("nothing");
        }

    }

}

Output


found Java!

1.2 For case insensitive, convert String to uppercase or lowercase before contains()

JavaExample2.java

package com.mkyong.example;

public class JavaExample2 {

    public static void main(String[] args) {

        String name = "mkyong is learning Java 123";

        if (name.toLowerCase().contains("java")) {
            System.out.println("found Java");
        } else {
            System.out.println("nothing");
        }

    }

}

Output


found Java!

2. String indexOf()

JavaExample3.java

package com.mkyong.concurrency;

public class JavaExample3 {

    public static void main(String[] args) {

        String name = "mkyong is learning Java 123";

        if (name.indexOf("Java") != -1) {
            System.out.println("found Java");
        } else {
            System.out.println("nothing");
        }

    }

}

Output


found Java!

References

  1. Java doc – String#contains
  2. Java doc – String#indexof

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar