Java String contains() Method
What is String?
A string class in Java is a collection of characters that a script interprets literally. A string is an object that symbolises a group of characters. It uses Java.lang. The String class is used to create a string object.
- Numerous methods, including compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), and substring(), are available in the Java String class.
To know more about String Class in java read the complete article.
String contains() Method:
The contains() method of the Java String class looks through the string’s characters in order. If the series of char values is present in the string, it returns true; otherwise, it returns false.
The Java String contains() method checks whether a string contains a sequence of characters and Returns true if the characters exist and false if not.
For example, you may check to see if the substring “PrepInsta” is included in the string “PrepInsta Prime is learning Platform.” Java’s string contains() function comes in handy in these circumstances.
- NullPointerException – if the returned value is null
Syntax:
public boolean contains(CharSequence s)
Parameters:
s - the sequence to search for
Let’s look at a string-related Java program where the Java String contains() method is used to perform an operation on the given string.
Example 1 : Determine whether a string contains a particular character sequence:
public class Main { public static void main(String[] args) { String myStr = "PrepInsta"; System.out.println(myStr.contains("Prep")); } }
Output
true
Example 2 : Determine whether a string contains a particular character sequence
public class Main { public static void main(String[] args) { String myStr = "Welcome to PrepInsta"; System.out.println(myStr.contains("Prep")); System.out.println(myStr.contains("Insta")); System.out.println(myStr.contains("Prime")); } }
Output
true true false
Examples 3: Determine whether a string contains a particular character sequence.
public class Main { public static void main(String[] args) { String myStr = "PrepInsta is a online learing platfrom"; System.out.println(myStr.contains("Learn")); System.out.println(myStr.contains("from")); System.out.println(myStr.contains("Insta")); System.out.println(myStr.contains("line")); } }
Output
false true true true
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment