Compare String In Java
Compare String
On the basis of content and reference, we can compare the string in Java.
On the basis of content and reference, we can compare the string in Java.
Three ways to compare the string in Java are,
- String compared by equals() method
The string in equals() method compares the original content of the string. It is mainly used to compare values of the string for the equality.
String class provides two methods, which are, - public boolean equals(Object another)
This method is used to compare the string to the specified object. - public boolean equalsIgnoreCase(String another)
This method is used to compare the string to another string by ignoring the case.
Let’s see an example, given below.
Code- public class CompareString {
- public static void main(String args[]) {
- String n1 = "Emily";
- String n2 = "Emily";
- String n3 = new String("Emily");
- String n4 = "Emilly";
- System.out.println(n1.equals(n2));
- System.out.println(n1.equals(n3));
- System.out.println(n1.equals(n4));
- }
- }
Output
Let’s see another example, given below.
Code- public class CompareString {
- public static void main(String args[]) {
- String n1 = "Peter";
- String n2 = "PETER";
- System.out.println(n1.equals(n2));
- System.out.println(n1.equalsIgnoreCase(n2));
- }
- }
Output - String compare by == operator
When the string is compared by = = operator, it compares the references only and not the values.
Let’s see an example, given below.
Code- public class CompareString {
- public static void main(String args[]) {
- String n1 = "Sophia";
- String n2 = "Sophia";
- String n3 = new String("Sophia");
- String n4 = new String("Sophia");
- String n5 = new String("Sophie");
- System.out.println(n1 == n2);
- System.out.println(n2 == n3);
- System.out.println(n3 == n4);
- System.out.println(n4 == n5);
- }
- }
Output - String compare by compareTo() method
When the string is compared by compareTo() method, it compares the values and returns an integer value, which describes when first string is less than, equal to or greater than second string, the output is retrieved accordingly.
Suppose n1 and n2 are two string variables and if - n1 == n2; it will return 0.
- n1 > n2; it will return a positive value.
- n1 < n2; it will return a negative value.
Let’s see an example, given below.
Code- public class CompareString {
- public static void main(String args[]) {
- String n1 = "James";
- String n2 = "James";
- String n3 = "John";
- System.out.println(n1.compareTo(n2));
- System.out.println(n2.compareTo(n3));
- System.out.println(n3.compareTo(n1));
- }
- }
Output
Summary
Thus, we learnt that on the basis of content and reference, we can compare the string in Java and also learnt their ways to compare the string in Java.