String comparison

String comparison

The relational operators cannot be used to compare the strings. On other hand, method like compareTo() and equals() should be used in string comparison.

Let us write a program to compare two strings using ‘==’ and see result

Program
class test
{
public static void main(String args[])
{
String s1=”Hello”;
String s2=new String(“Hello”);
if(s1==s2)
System.out.println(“Both are same”);
else
System.out.println(“Not same”);
}
}

Output:
Not same

When an object is created by JVM, it returns the memory address of the object as a hexadecimal number, which is called object reference.

In fact that both string are same. We are getting wrong output. In first string , when JVM creates an object with a reference number and when JVM creates an another object with new operator it creates a another reference number. So the statement (s1==s2) will compares only reference number and both reference number are not same and hence output will be “Not same”.

Actually, to compare the contents of string object we should use ‘equals()’ method.

Program
class test
{
public static void main(String args[])
{
String s1=”Hello”;
String s2=new String(“Hello”);
if(s1.equals(s2))
System.out.println(“Both are same”);
else
System.out.println(“Not same”);
}
}

Output:
Both are same


What is difference between == and equals() while comparing string? Which one is reliable?

== operator compares the reference of the string objects. equals() method compares the content of the object. While computing the strings equals() method should be used as it yield the correct result.


 

 

Leave a Reply

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