Searching characters and substring in a String in Java

Following is the Java program to search characters and substring in a string −


 Live Demo

import java.lang.*;
public class Demo {
   public static void main (String[] args) {
      String test_str = "Hello";
      CharSequence seq = "He";
      boolean bool_1 = test_str.contains(seq);
      System.out.println("Was the substring found? " + bool_1);
      boolean bool_2 = test_str.contains("Lo");
      System.out.println("Was the substring found? " + bool_2);


Was the substring found? true
Was the substring found? False

A class named Demo contains the main function. Here, a string is defined, and a CharSequence instance is created. The ‘contains’ function associated with the string is used to check if the original string contains the specific substring. It is then printed on the screen.

Updated on: 14-Sep-2020


Kickstart Your Career

Get certified by completing the course

Get Started