In this Java tutorial, you will learn how to check if two strings are equal using String.equals()
, or String.equalsIgnoreCase()
methods, with examples.
Java – Check if two Strings are Equal
You can check if two strings are equal, by considering case or not considering the case, in your Java application.
In this tutorial, we shall see how to check if two Strings are equal in Java using the method String.equals(String anotherString).
Also, we shall go through an example Java program to ignore the case of the characters in the string, and check if two Strings are equal.
Examples
1. Check if two strings are equal
In the following example, we defined two strings, and then used String.equals() method. If two string are equal, which is an yes in the below example, equals() method returns true, else false.
Example.java
public class Example {
public static void main(String[] args) {
// string declaration
String str1 = "Hello World";
String str2 = "Hello World";
// str1.equals(str2) method returns true if str1 has same characters as that of str2
boolean areTwoStringsEqual = str1.equals(str2);
System.out.println("Are two strings equal : "+areTwoStringsEqual);
}
}
When the program is run, the output to the console would be as shown below.
Output
Are two strings equal : true
2. Check if two strings are equal
This example is same as that of previous one, but here we are reading strings entered by the user in console input.
Example.java
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System. in);
//read first string
System.out.print("Enter first string : ");
String str1 = scanner.nextLine();
//read second string
System.out.print("Enter second string : ");
String str2 = scanner.nextLine();
//check if two strings are equal
boolean areTwoStringsEqual = str1.equals(str2);
System.out.print("Two strings are equal : "+areTwoStringsEqual);
}
}
When the program is run, the output to the console is as shown in the following.
Output
Enter first string : good morning
Enter second string : good morning
Two strings are equal : true
3. Ignore case & check if strings are equal
In this example, we shall ignore the case of the characters in two strings and check if strings are equal usgin equalsIgnoreCase() method of String class.
Example.java
public class Example {
public static void main(String[] args) {
// string declaration
String str1 = "Hello World";
String str2 = "hello world";
//ignore case and check if strings are equal
boolean areTwoStringsEqual = str1.equalsIgnoreCase(str2);
System.out.println("Two strings are equal : "+areTwoStringsEqual);
}
}
Run the program. As two strings are equal when you ignore the case, equalsIgnoreCase() should return true for the above example.
Output
Two strings are equal : true
Conclusion
In this Java Tutorial, we learned how to check if two strings are equal in Java, by considering the case of characters or ignoring it.