Compare Strings Java


String class is a boon to Java programmers given by the designers. Lot of trouble you have taken with volumes of code in C/C++, just forget in Java. Good example is Compare Strings in Java.

Everywhere, in every language, strings comparison is required at every stage. To compare strings, there are two styles – using == and equals() method. Generally programmer prefers the usage of equals() method and not ==. The difference is clearly discussed in this Web site already under Introduction – Immutable Nature – Comparison.

Prefer to use equals() method to compare two stings and not logical equals == as == evaluates referring to their locations, which sometimes, goes wrong evaluation even though both strings are same.

Following program on Compare Strings Java uses equals() method. equals() method returns a boolean value of true if both strings are same or false, if both have different characters.
public class Demo
{
  public static void main(String args[])
  {
    String str1 = "hello";
    String str2 = "hello";
    String str3 = "world";
    String str4 = "Hello";
                                                                                     // now start Compare Strings pairs
    boolean b = str1.equals(str2);
    System.out.println("hello and hello are equal: " + b);                           // prints true
                                                                                     // this way also can be done, just for printing purpose
    System.out.println("hello and hello are equal: " + str1.equals(str2));           // prints true
    System.out.println("hello and world are equal: "+ str1.equals(str3));            // prints false
    System.out.println("hello and Hello are equal: "+ str1.equals(str4));            // prints false, hello is different from Hello
    System.out.println("hello and Hello are equal (case-insensitive): "+ str1.equalsIgnoreCase(str4)); // prints true
                                                                                     // you can do like this also
    System.out.println("hello and world are equal: "+ "hello".equals("world"));      // prints false
  }
}


Compare Strings
Output screenshot on Compare Strings Java

equals() method belongs to Object class and overridden by String class. equals() method does case-sensitive comparison. equalsIgnoreCase() is defined in String class itself. This method does case-insensitive comparison.

Leave a Comment

Your email address will not be published.