Compare Strings Java

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.


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 Reply

Your email address will not be published. Required fields are marked *