i

JAVA Complete Course

String Comparison

There are few ways of comparing Strings in java and they are also different in the way how strings are compared. One of the way for comparing to strings is equals() method which compares contents.

Using String.equals(): In Java, to compare two  strings based on the data/content of the string, we should use equals() method. If each character of both strings are same then it returns true. If at least one character does not match, then it returns false.

string1.equals(string2);

There is another method equalsIgnoreCase() which is doing logically same operation like equals but it compares strings in case insensitive way. To compare two strings irrespective of the case (lower or upper) of the string, we need to use String.equalsIgnoreCase() method. This method will return true if the argument is different than null and the contents of both the Strings are containing same characters in different registry (upper and lower cases), else false. For example:

“Giga”.equalsIgnoreCase(“giGa”) will return true;

There is  equals method in Object class which is static and comparing two strings. Object.equals(Object a, Object b) is the method from Object class and it returns true if the both of arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if only one argument is null, false is returned. In other case, equality of arguments will be determined by using the equals() method of the first argument.

There might be a question about “==” operator. But this operator works in a bit different way. It doesn’t compare the content of strings. It compares the references (address in the memory). “==” will give us true if only both variables are referring to the same objects in memory.