Java String compare
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:
- By
equals() method
- By
= = operator
- 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. }
Output:true
true
false
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s3));//true
8. }
9. }
Output:false
true
Click me for more about equals()
method
2) String compare by == operator
The = = operator compares
references not values.
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }
Output:true
false
3) String compare by compareTo() method
The String compareTo() method
compares values lexicographically and returns an integer value that describes
if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two
string variables. If:
- s1
== s2 :0
- s1
> s2
:positive value
- s1
< s2
:negative value
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }
Output:0
1
-1
Click me for more about compareTo()
method
No comments:
Post a Comment