Introduction
In this lab, you will learn how to check if a string contains a specific substring in Java. We will explore different methods for this common task, starting with the straightforward contains() method. You will learn how to use contains() to determine if a string includes a given sequence of characters and practice implementing this in a simple Java program.
Following the introduction to contains(), the lab will guide you through using the indexOf() method to not only check for the presence of a substring but also to find its position within the string. Finally, you will learn techniques to perform case-insensitive substring checks, ensuring your code can handle variations in capitalization. By the end of this lab, you will have a solid understanding of various approaches to substring checking in Java.
Use contains() to Search for a Substring
In this step, we will learn how to check if a string contains a specific substring in Java using the contains() method. This is a common task in programming, for example, when searching for a keyword in a sentence or checking if a file name contains a certain extension.
The contains() method is part of the String class in Java. It returns true if the string contains the specified sequence of characters, and false otherwise.
Let's create a new Java file to practice using contains().
Open the File Explorer on the left side of the WebIDE.
Make sure you are in the
~/projectdirectory.Right-click in the empty space and select "New File".
Name the new file
StringContains.java.Open the
StringContains.javafile in the editor.Copy and paste the following code into the editor:
public class StringContains { public static void main(String[] args) { String sentence = "Java programming is fun and powerful."; String keyword = "programming"; // Check if the sentence contains the keyword boolean containsKeyword = sentence.contains(keyword); System.out.println("Sentence: \"" + sentence + "\""); System.out.println("Keyword: \"" + keyword + "\""); System.out.println("Does the sentence contain the keyword? " + containsKeyword); String anotherKeyword = "Python"; boolean containsAnotherKeyword = sentence.contains(anotherKeyword); System.out.println("\nAnother keyword: \"" + anotherKeyword + "\""); System.out.println("Does the sentence contain the another keyword? " + containsAnotherKeyword); } }In this code:
- We declare a
Stringvariablesentenceand aStringvariablekeyword. - We use
sentence.contains(keyword)to check ifsentencecontains the sequence of characters inkeyword. The result is stored in abooleanvariablecontainsKeyword. - We print the original sentence, the keyword, and the result of the
contains()check. - We repeat the process with a different keyword, "Python", to see the result when the substring is not found.
- We declare a
Save the file (Ctrl+S or Cmd+S).
Open the Terminal at the bottom of the WebIDE.
Make sure you are in the
~/projectdirectory using the command:cd ~/projectCompile the Java program using the
javaccommand:javac StringContains.javaIf there are no errors, you will not see any output. A
StringContains.classfile will be created in the~/projectdirectory.Run the compiled Java program using the
javacommand:java StringContainsYou should see output similar to this:
Sentence: "Java programming is fun and powerful." Keyword: "programming" Does the sentence contain the keyword? true Another keyword: "Python" Does the sentence contain the another keyword? false
This output shows that the contains() method correctly identified that the sentence contains "programming" but not "Python".
Explore indexOf() for Substring Position
In the previous step, we learned how to check if a string contains a substring using contains(). Now, let's explore another useful method, indexOf(), which not only tells us if a substring exists but also gives us its starting position within the string.
The indexOf() method in Java's String class returns the index within the string of the first occurrence of the specified substring. The index is the position of the first character of the substring. Remember that in programming, indexing usually starts from 0. If the substring is not found, indexOf() returns -1.
Let's modify our previous Java file, StringContains.java, to use the indexOf() method.
Open the
StringContains.javafile in the WebIDE editor.Replace the entire contents of the file with the following code:
public class StringContains { public static void main(String[] args) { String sentence = "Java programming is fun and powerful."; String keyword = "programming"; // Find the index of the keyword int index = sentence.indexOf(keyword); System.out.println("Sentence: \"" + sentence + "\""); System.out.println("Keyword: \"" + keyword + "\""); if (index != -1) { System.out.println("The keyword \"" + keyword + "\" was found at index: " + index); } else { System.out.println("The keyword \"" + keyword + "\" was not found."); } String anotherKeyword = "Python"; int anotherIndex = sentence.indexOf(anotherKeyword); System.out.println("\nAnother keyword: \"" + anotherKeyword + "\""); if (anotherIndex != -1) { System.out.println("The keyword \"" + anotherKeyword + "\" was found at index: " + anotherIndex); } else { System.out.println("The keyword \"" + anotherKeyword + "\" was not found."); } } }In this updated code:
- We use
sentence.indexOf(keyword)to find the starting index of thekeywordwithin thesentence. The result is stored in anintvariableindex. - We use an
ifstatement to check if the returnedindexis -1. If it's not -1, it means the keyword was found, and we print its index. Otherwise, we print a message indicating that the keyword was not found. - We repeat the process for "Python" to demonstrate the case where the substring is not present.
- We use
Save the file (Ctrl+S or Cmd+S).
Open the Terminal at the bottom of the WebIDE.
Make sure you are in the
~/projectdirectory.Compile the modified Java program:
javac StringContains.javaRun the compiled Java program:
java StringContainsYou should see output similar to this:
Sentence: "Java programming is fun and powerful." Keyword: "programming" The keyword "programming" was found at index: 5 Another keyword: "Python" The keyword "Python" was not found.
The output shows that "programming" starts at index 5 in the sentence (remembering that 'J' is at index 0, 'a' is at index 1, and so on, including the space). It also correctly indicates that "Python" was not found.
Using indexOf() is a powerful way to not only check for the presence of a substring but also to determine its exact location, which can be useful for various string manipulation tasks.
Make Substring Check Case-Insensitive
In the previous steps, we used contains() and indexOf() to search for substrings. However, these methods are case-sensitive. This means that "Java" is considered different from "java" or "JAVA". In many situations, you might want to perform a case-insensitive search.
Java's String class doesn't have a built-in method like containsIgnoreCase() or indexOfIgnoreCase(). However, we can achieve case-insensitivity by converting both the original string and the substring to the same case (either lowercase or uppercase) before performing the search. The most common approach is to convert both to lowercase using the toLowerCase() method.
Let's modify our StringContains.java file again to perform a case-insensitive search.
Open the
StringContains.javafile in the WebIDE editor.Replace the entire contents of the file with the following code:
public class StringContains { public static void main(String[] args) { String sentence = "Java programming is fun and powerful."; String keyword = "JAVA"; // Using uppercase for demonstration // Convert both strings to lowercase for case-insensitive comparison String lowerSentence = sentence.toLowerCase(); String lowerKeyword = keyword.toLowerCase(); // Use contains() on the lowercase strings boolean containsKeyword = lowerSentence.contains(lowerKeyword); System.out.println("Original Sentence: \"" + sentence + "\""); System.out.println("Original Keyword: \"" + keyword + "\""); System.out.println("Does the sentence contain the keyword (case-insensitive)? " + containsKeyword); // You can also use indexOf() in a case-insensitive way int index = lowerSentence.indexOf(lowerKeyword); if (index != -1) { System.out.println("The keyword \"" + keyword + "\" was found at index (case-insensitive): " + index); } else { System.out.println("The keyword \"" + keyword + "\" was not found (case-insensitive)."); } } }In this code:
- We define the
keywordas "JAVA" (uppercase). - We create new strings
lowerSentenceandlowerKeywordby converting the original strings to lowercase usingtoLowerCase(). - We then use the
contains()method on the lowercase strings to perform a case-insensitive check. - We also demonstrate how to use
indexOf()in a case-insensitive manner by applying it to the lowercase strings.
- We define the
Save the file (Ctrl+S or Cmd+S).
Open the Terminal at the bottom of the WebIDE.
Make sure you are in the
~/projectdirectory.Compile the modified Java program:
javac StringContains.javaRun the compiled Java program:
java StringContainsYou should see output similar to this:
Original Sentence: "Java programming is fun and powerful." Original Keyword: "JAVA" Does the sentence contain the keyword (case-insensitive)? true The keyword "JAVA" was found at index (case-insensitive): 0
This output shows that even though the original keyword was "JAVA" (uppercase), the case-insensitive search correctly found it in the sentence and reported its index (which is 0 for "Java" in lowercase).
By converting strings to a consistent case before searching, you can easily perform case-insensitive substring checks in Java.
Summary
In this lab, we learned how to check if a string contains a specific substring in Java. We started by using the contains() method, which provides a simple boolean check for the presence of a substring. This method is straightforward and useful for basic substring existence checks.
We then explored the indexOf() method, which not only checks for the presence of a substring but also returns the starting index of the first occurrence. This allows for more detailed analysis of the substring's position within the string. Finally, we addressed the common requirement of performing case-insensitive substring checks, demonstrating techniques to achieve this regardless of the original string's casing.



