Java String contains() method
contains() method returns true only if it contains the given sequence of characters otherwise it returns false.
syntax:
public boolean contains(CharSequence sequence)
parameters:
sequence : It is the sequence to be searched.
Returns:
It returns true when specified sequence character is found, Otherwise it returns false
Throws:
NullPointerException :when the sequence of characters is not found.
Example 1:
public class ContainsEx1
{
public static void main(String args[])
{
String name="tutorial and example";
System.out.println(name.contains("tutorial"));
System.out.println(name.contains("and "));
System.out.println(name.contains("and"));
System.out.println(name.contains("guide"));
System.out.println(name.contains("example"));
System.out.println(name.contains(" "));
}
}
Output:
true false true false true true
Example 2: Case Sensitive
public class ContainsEx2
{
public static void main(String[] args)
{
String str = "Tutorial And Example World";
boolean isContains = str.contains("World");
System.out.println(isContains);
if(str.contains("And1")){
System.out.println("Welcome to the Java Tutorial and Example");
}else{
System.out.println("J -->"+str.contains("And1"));
}
System.out.println(str.contains("Tutorial And Example"));
// Case Sensitive
System.out.println(str.contains("Tutorial and Example")); // false
}
}
Output:
true J-->false true false
Example 3: Case Insensitive
public class ContainsEx3 {
public static void main(String[] args) {
String str = "tutorialandexample world";
String str1 = "TUToRIalaNdExAmPLe WOrLd";
System.out.println("Case Check: " + str.contains(str1.toLowerCase()));
}
}
Output:
Case Check: true