Search Your Topic

Monday, 24 July 2017 04:06

Java String compare

Written by
Rate this item
(0 votes)

We can compare string in java 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 in java:

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

1) String compare by equals() method

The String 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.
  1. class Teststringcomparison1{  
  2.  public static void main(String args[]){  
  3.    String s1="Sachin";  
  4.    String s2="Sachin";  
  5.    String s3=new String("Sachin");  
  6.    String s4="Saurav";  
  7.    System.out.println(s1.equals(s2));//true  
  8.    System.out.println(s1.equals(s3));//true  
  9.    System.out.println(s1.equals(s4));//false  
  10.  }  
  11. }  
  1. class Teststringcomparison2{  
  2.  public static void main(String args[]){  
  3.    String s1="Sachin";  
  4.    String s2="SACHIN";  
  6.    System.out.println(s1.equals(s2));//false  
  7.    System.out.println(s1.equalsIgnoreCase(s3));//true  
  8.  }  
  9. }  
Read 1128 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email :

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.

Java Training