String Comparison in Java

The String Comparison in Java is one of the most commonly asked question in interviews. It may be twisted as, differences between Java equals Method and == Operator.

In this article we will show you, How to Perform String Comparison in Java Programming Language. Before we get into practical example, let us see the major difference:

Java equals Method compare the string data with user specified Object data to check whether they both represent the same sequence of characters or not. In shortly, it will compare the string values and based on the result it will return Boolean True or False.

== Operator compares the Object reference of one string with another and returns the result.

How to Perform String Comparison in Java

In this Java program, We are going to perform Java string comparison. Here, we will compare two strings using both string.equals method and == operator.

Following statement will call the public boolean equals (Object Obj) method to compare the string str1 with str2. From the above screenshot you can observe that, it is returning True because String is an Object.

boolean a = str1.equals(str2);

In this Java String Comparison example, the following statement will compare the string literal str1 with str2. From the above screenshot you can observe that, it is returning True because both of them refers to same Object in memory

The following statements will compare the string Object str3 with another string object str4. From the above screenshot you can observe that,

First statement returns True because the string value in both str3 and str4 are same.

Second statement returns False. Though the string value is same == operator is returning False because, str3 is creating new object in Cache and str4 is creating another new object in Cache. It means the object reference of str3 and str4 is different so, it is returning False.

Below statement in this Java String Comparison example will compare the string literal str1 with String object str5. From the above screenshot you can observe that,

First statement returns True because the string value in both str1 and str5 are same.

Second statement returns False. Though the string value is same == operator is returning False because, str1 is creating object inside the memory and str5 is creating new object in Cache. It means the object reference of str1 and str5 is different so, it is returning False.