String comparison in Java by R4R Team

 String comparison in Java:

We can compare two given strings on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.

There are three ways to compare String objects:

1)By equals() method
2)By = = operator
3)By compareTo() method


1) By equals() method:

equals() method compares the original content of the string.It compares values of string for equality.String class provides two methods:
public boolean equals(Object another){} compares this string to the specified object.
public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case.
 

class stringtest{

public static void main(String args[]){

String s1="deepak";

String s2="deepak";

String s3=new String("deepak");

String s4="Saurav";

System.out.println(s1.equals(s2));//true

System.out.println(s1.equals(s3));//true

System.out.println(s1.equals(s4));//false

} }


Example of equalsIgnoreCase(String) method
 

class stringtest2{

public static void main(String args[]){

String s1="deepak";

String s2="DEEPAK";

System.out.println(s1.equals(s2));//false

System.out.println(s1.equalsIgnoreCase(s3));//true

} }


2) By == operator


The = = operator compares references not values.
Example of == operator
 

class Teststring{

public static void main(String args[]){

String s1="deepak";

String s2="deepak";

String s3=new String("deepak");

System.out.println(s1==s2);//true (because both refer to same instance)

System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)

} }

3) By compareTo() method:

compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than.
Suppose s1 and s2 are two string variables.If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
Example of compareTo() method:
 

class Testcomparison{

public static void main(String args[]){

String s1="deepak";

String s2="deepak";

String s3="Rajan";

System.out.println(s1.compareTo(s2));//0

System.out.println(s1.compareTo(s3));//1(because s1>s3)

System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )

} }

Leave a Comment: