Check whether a string is equal to another string in Java
equals(String str) and equalsIgnoreCase(String str) methods of String class can be used to check whether a String is equal to another String in Java.
Both these methods will return true when both the strings are same and returns false if both are not same. i.e return type of the method is boolean.
If we want to consider uppercase (capital letters) and lowercase (small letters), we can use equals(String str) method and if we want to ignore the cases, we can use equalsIgnoreCase(String str)
Example 1
class StringTest{
public static void main(String args[]){
String str="Superb";
boolean isEqual=str.equals("superb");
if(isEqual==true){
System.out.println("Both are equal");
}
else{
System.out.println("Both are not equal");
}
}
}
Output 1
Both are not equal
Example 2
class StringTest{
public static void main(String args[]){
String str="Superb";
boolean isEqual=str.equalsIgnoreCase("superb");
if(isEqual==true){
System.out.println("Both are equal");
}
else{
System.out.println("Both are not equal");
}
}
}
Output 2
Both are equal