Java: Compare a given string to the specified character sequence
Java String: Exercise-9 with Solution
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:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to test if a given string contains the specified sequence of char values.
Next: Write a Java program to compare a given string to the specified string buffer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/string/java-string-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics