Monday 25 November 2013

Use Equals methods for comparing String in Java


String class overrides equals method and provides a content equality, which is based on characters, case and order. So if you want to compare two String object, to check whether they are same or not, always use equals() method instead of equality operator. Like in earlier example if  we use equals method to compare objects, they will be equal to each other because they all contains same contents. Here is example of comparing String using equals method.

String name = "Java"; //1st String object
String name_1 = "Java"; //same object referenced by name variable
String name_2 = new String("Java") //different String object

if(name.equals(name_1)){
System.out.println("name and name_1 are equal String by equals method");
}

//this will return false
if(name==name_2){
System.out.println("name_1 and name_2 are equal String by equals method");
}


Difference between == and equals method in Java

Now we know what is equals method, how it works and What is equality operator (==) and How it compare objects, its time to compare them. Here is some worth noting difference between equals() method and == operator in Java:

·          First difference between them is, equals() is a method defined inside the java.lang.Object class and == is one type of operator and you can compare both primitive and objects using equality operator in Java.

·          Second difference between equals and == operator is that, == is used to check reference or memory address of the objects whether they point to same location or not, and equals() method is used to compare the contents of the object e.g. in case of comparing String its characters, in case of Integer its there numeric values etc. You can define your own equals method for domain object as per business rules e.g. two Employes objects are equal if there EmployeeId is same.

·          Third difference between equals and == operator is that, You can not change the behavior of == operator but we can override equals() method and define the criteria for the objects equality.

Let clear all these differences between equals and == operator using one Java example :

String s1=new String("hello");
String s2=new String("hello");


Here we have created two string s1 and s2 now will use == and equals () method to compare these two String to check whether they are equal or not.


No comments:

Post a Comment