w3resource

Java: Test if a given string contains the specified sequence of char values

Java String: Exercise-8 with Solution

Write a Java program to test if a given string contains the specified sequence of char values.

Visual Presentation:

Java String Exercises: Test if a given string contains the specified sequence of char values

Sample Solution:

Java Code:

// Define a public class named Exercise8.
public class Exercise8 {
    // Define the main method.
    public static void main(String[] args) {
        // Declare and initialize two string variables, str1 and str2.
        String str1 = "PHP Exercises and Python Exercises";
        String str2 = "and";
        
        // Print the original string.
        System.out.println("Original String: " + str1);
        // Print the specified sequence of char values.
        System.out.println("Specified sequence of char values: " + str2);
        
        // Check if str1 contains the sequence specified in str2 and print the result.
        System.out.println(str1.contains(str2));
    }
}

Sample Output:

Original String: PHP Exercises and Python Exercises                                                           
Specified sequence of char values: and                                                                        
true 

Flowchart:

Flowchart: Java String  Exercises - Test if a given string contains the specified sequence of char values

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to concatenate a given string to the end of another string.
Next: Write a Java program to compare a given string to the specified character sequence.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.