Wednesday, 1 February 2017

STRING COMPARISON IN JAVA

We can compare strings in java in three different ways –

1. By equals() method – It is used to compare the original content of the string and its values for equality. We can compare in two ways either by ignoring string case or simple maintaining the case. It gives the output in the form of true and false.

Example –
public class String1 {
          public static void main(String[] args) {
                   String s1 ="hello";
                   String s2 ="HELLO";
                   String s3 ="Java";
                   System.out.println(s1.equals(s2));
                   System.out.println(s1.equalsIgnoreCase(s2));
                   System.out.println(s1.equalsIgnoreCase(s3));
          }
}

Output –
false
true
false


2. By ==operator – It basically compares reference not the values.

Example –
public class String1 {
          public static void main(String[] args) {
                   String s1 ="hello";
                   String s2 ="hello";
                   String s3 = new String("hello");
                   System.out.println(s1==s2);
                   System.out.println(s1==s3);
                   System.out.println(s1.equals(s3));
          }
}

Output –
true
false
true


3. By compareTo() method – It compares a value lexicographically and returns the value as integer in the form of less than, equal to or greater than. If s1==s2 then result is 0, s1>s2 then result is positive value and if s1<s2 then result is negative value

Example –
public class String1 {
          public static void main(String[] args) {
                   String s1 ="hello";
                   String s2 ="hello";
                   String s3 = "tata";
                   System.out.println(s1.compareTo(s2)); // 0
                   System.out.println(s1.compareTo(s3)); // negative value
                   System.out.println(s3.compareTo(s1)); // positive value          
          }
}

Output –
0
-12
12

No comments:

Post a Comment