Java: Compare a given string to another string, ignoring case considerations
Write a Java program to compare a given string to another string, ignoring case considerations.
Visual Presentation:
Sample Solution:
Java Code:
// Define a public class named Exercise14.
public class Exercise14 {
// Define the main method.
public static void main(String[] args) {
// Declare and initialize three string variables.
String columnist1 = "Stephen Edwin King";
String columnist2 = "Walter Winchell";
String columnist3 = "stephen edwin king";
// Test if columnist1 is equal to columnist2 ignoring case.
boolean equals1 = columnist1.equalsIgnoreCase(columnist2);
// Test if columnist1 is equal to columnist3 ignoring case.
boolean equals2 = columnist1.equalsIgnoreCase(columnist3);
// Display the results of the equality checks.
System.out.println("\"" + columnist1 + "\" equals \"" +
columnist2 + "\"? " + equals1);
System.out.println("\"" + columnist1 + "\" equals \"" +
columnist3 + "\"? " + equals2);
}
}
Sample Output:
"Stephen Edwin King" equals "Walter Winchell"? false "Stephen Edwin King" equals "stephen edwin king"? true
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to compare two strings for equality ignoring case and any leading/trailing spaces.
- Write a Java program to check if two strings are equal when converted to uppercase, and then reverse each.
- Write a Java program to compare two strings for equality while also ignoring any numeric characters.
- Write a Java program to test case-insensitive equality on strings that include mixed Unicode characters.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to check whether two String objects contain the same data.
Next: Write a java program to print current date and time in the specified format.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics