Java String contains() method was introduced in java 1.5 release as a utility method.
This method returns true if the string contains the specified sequence of char values. Else it returns false.
Note that string contains() method is case sensitive, so "credit".contains("C"); will return false.
The argument of String contains() method is java.lang.CharSequence, so any implementation classes are also fine as argument, such as StringBuffer, StringBuilder and CharBuffer.
For case insensitive check, we can change both the strings to either upper case or lower case before calling the contents() method.
package com.csi.collectionconcept;
import java.util.ArrayList;
import java.util.Scanner;
public class ContainsMethodConcept {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter Product Name to check availability: ");
String productName = sc.next();
ArrayList productList = new ArrayList<>();
productList.add("MI");
productList.add("LENOVO");
productList.add("DELL");
productList.add("APPLE");
productList.add("HP");
if (productList.contains(productName)) {
System.out.println("Product is available");
} else {
System.out.println("Product is not available");
}
}
}
Output: Please enter Product Name to check availability: MI Product is available |