Equals() and EqualsIgnoreCase() Method In Java Experimented And Explained (Java String Methods)

 Equals() and EqualsIgnoreCase() Method In Java Experimented And Explained (Java String Methods)


There are various predefined string functions(methods) in Java.

In this post we will explore two methods : equals() and equalsIgnoreCase().

equals() :

This method compares two string and returns true if both the strings are equal and returns false if both the strings are not equal.

Note : equals() is case sensitive i.e "A" and  "a" are not equal.

Syntax :  string1.equals(string2);

equalsIgnoreCase() :

This methos compares two string and returns true if both the strings are equal and returns false if both the strings are not equal.

The difference between equals() and equalsIgnoreCase() is that equalsIgnoreCase() ignores the case i.e "A"  and "a" are equals in equalsIgnoreCase() method.

Syntax : string1.equalsIgnoreCase(string2);


Java Example Code :


public class EqualsAndEqualsIgnoreCase 
{

public static void main(String[] args) 
{
String s1="Learn Programming";
String s2="learn programming";

//equals()

System.out.println(s1.equals(s2));  //returns false since equals will check case too i.e l and p mismatching

System.out.println(s1.equals("Learn Programming"));  //returns true since both are equal

System.out.println(s1.equals("Learn"));  //returns false 
//equalsIgnoreCase()

System.out.println(s1.equalsIgnoreCase(s2));  //returns true since it ignores case 

System.out.println(s1.equalsIgnoreCase("Learn Programming"));  //return true 

System.out.println(s1.equalsIgnoreCase("learn"));  //returns false
}

}



Output :



Previous Post
Next Post
Related Posts

0 comments:

Popular Posts