String Comparison in Java

Posted on Updated on

The relational operator like >, <, =, >=, <=, == and != can’t be used to compare the String on the other hand we can use the comapreTo() and equals() method in String comparison in java.

Let compare a String using == comparator and see the result –



In spite of the fact that both String are same but we are getting wrong output in the program why ?

When we created the first String str1 = “Code2Succeed”;, JVM executes the statement, it created an object in heap memory and stores the “Code2Succeed” in it. Suppose a reference number ‘4d5f6’ is allotted for this object.

Similarly, for second String str2 = new String(“Code2Succeed”);, JVM executes the statement, it created another object and stores the “Code2Succeed” in another reference number say ‘54865g’.

Therefore the statement if(str1 == str2) will compare these reference number i.e. ‘4d5f6’ & ‘54865g’. Since both are not same and hence the output is also not same. So, conceptually we should compare the content of these string object not their references.

When an object is created by JVM, it returns the memory address of the object as a hexadecimal number which is called as object reference. When a new object is created, a new reference number is allotted to it. It mean every object will have unique reference.

See the below figure for comparison the String using == and equals() –

String Compariosn




Now, Let’s rewrite the earlier program with a slight change in creation of String –



Now, we can see using == operator give us the output as both are same why ?

First String creation – String str1 = “Code2Succeed”;

Here, JVM creates a String object and stores “Code2Succeed” in it. Observe for second, we are not using new operator to create string. We are using assignment operator(=). So when ‘=’ to create string object, JVM uses a separate block of memory which is called ‘*string constant pool‘.

When the next statement, String str2 = “Code2Succeed”; is executed by the JVM, it searches in the string constant pool to know whether the object with same content is already available there or not. Since the same object is already available there (which is str1), then JVM does not create another object. It simply created another reference variable (str2) to the same object, and copies the reference number of str1 into str2. So we have same value in both string. Hence the output both are same.


*string constant pool – It is separate block of memory where the string object are held by JVM. If the string object is created directly, using assignment operator as String str 1 = “Code2Succeed”, then it is stored in string constant pool.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.