Check the presence of Substring in a String in java
In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes.
Example: ” Omsairam”
Substring
The part of the string is called the substring. Java String class contains an inbuilt method substring(), which is used for accessing a particular part of the string.
Example: Sachin Tendulkar. In this example, Tendulkar is the substring.
A string is defined as a group/collection of words. To access a particular word, some methods should be followed. In Java, String is a class and also a Datatype. To get a word from a string, there are two methods, which are as follows:
- IndexOf( )
- Contains( )
These two methods are from the String class in java.
IndexOf() method
This method is used to find the index of the string we need to find. It finds the index of that in the main String. The result is the index of the substring, an integer that returns -1 if the word or substring is not present in the string.
Consider an example for index() of method :
//Program
public class Word{
public static void main(String[] args){
String str = "Java is Object Oriented Programming Language";
System.out.println(str);
// check whether the word present in it or not
String word = "is Object";
int i = str.indexOf(word);
if(i>0)
System.out.println(str.substring(i, i+word.length()));
else
System.out.println("string not found");
}
}
Output

2.Contains( ) method
This method is also used to check whether the string contains the given the word.
The result of this method is a Boolean value, true or false. The result will be true if
It is found. Else it returns false.
Example
public class Word {
public static void main(String[] args){
String str = "Java is a object oriented programming language";
System.out.println(str);
// check the in substring in a string
String ss = "programming";
boolean val = str.contains(ss);
if(val)
System.out.println("String found: "+ss);
else
System.out.println("String Not found");
}
}
Output
