w3resource

Java: Compare a given string to the specified character sequence


9. Compare with Char Sequence

Write a Java program to compare a given string to the specified character sequence.

Sample Solution:

Java Code:

// Define a public class named Exercise9.
public class Exercise9 {
    // Define the main method.
    public static void main(String[] args) {
        // Declare and initialize two string variables, str1 and str2.
        String str1 = "example.com", str2 = "Example.com";
        
        // Create a CharSequence object named cs with value "example.com".
        CharSequence cs = "example.com";
        
        // Compare str1 and cs for content equality and print the result.
        System.out.println("Comparing " + str1 + " and " + cs + ": " + str1.contentEquals(cs));
        
        // Compare str2 and cs for content equality and print the result.
        System.out.println("Comparing " + str2 + " and " + cs + ": " + str2.contentEquals(cs));
    }
}
    

Sample Output:

Comparing example.com and example.com: true                                                                   
Comparing Example.com and example.com: false

Flowchart:

Flowchart: Java String  Exercises - Compare a given string to the specified character sequence


For more Practice: Solve these Related Problems:

  • Write a Java program to compare a string with a character sequence stored in a StringBuilder object.
  • Write a Java program to determine if a given string exactly matches a sequence of characters from user input.
  • Write a Java program to compare two character sequences for equality without converting them into strings.
  • Write a Java program to check if a string and a CharSequence are equal when ignoring non-alphanumeric characters.

Go to:


PREV : Contains Specified Sequence.
NEXT : Compare with StringBuffer.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Based on 68 votes, average difficulty level of this exercise is Hard .

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.