1. Introduction
In this tutorial, we are going to write a Java program to check if a given string contains a specified substring. This is a common operation performed in string manipulation and is quite useful in scenarios such as searching through text, validating user input, and implementing search features.
2. Program Steps
1. Define the main method as the program’s entry point.
2. Initialize the main string and the substring we want to search for.
3. Use the contains method of the String class to check if the main string contains the specified substring.
4. Print the result.
3. Code Program
public class SubstringChecker {
public static void main(String[] args) {
// Step 2: Initialize the main string and the substring we want to search for
String mainString = "Java Programming Language";
String substring = "Program";
// Step 3: Use the contains method to check if the main string contains the substring
boolean containsSubstring = mainString.contains(substring);
// Step 4: Print the result
System.out.println("Does the main string contain the substring? " + containsSubstring);
}
}
Output:
Does the main string contain the substring? true
4. Step By Step Explanation
– Step 1: The main method is defined, marking the entry point of the program.
– Step 2: Two strings, mainString and substring, are initialized with the values "Java Programming Language" and "Program" respectively.
– Step 3: The contains method of the String class is used to check if mainString contains substring. The result is stored in the boolean variable containsSubstring.
– Step 4: The result, stored in containsSubstring, is printed to the console.
In this program, we use the contains method provided by Java’s String class to easily check if a string contains a specified substring, and print the result.