Wednesday, June 8, 2016

Examples to compare strings in Java?

== compares Object reference
.equals() compares String value
Sometimes == gives illusions of comparing String values, in following cases
String a="Test";
String b="Test";
if(a==b) ===> true
This is a because when you create any String literal, JVM first searches for that literal in String pool, if it matches, same reference will be given to that new String, because of this we are getting
(a==b) ===> true
                       String Pool
     b -----------------> "test" <-----------------a
== fails in following case
String a="test";
String b=new String("test");
if (a==b) ===> false
in this case for new String("test") the statement new String will be created in heap that reference will be given to b, so b will be given reference in heap not in String Pool. Now a is pointing to String in String pool while b is pointing to String in heap, because of that we are getting
if(a==b) ===> false.
                String Pool
     "test" <-------------------- a

                   Heap
     "test" <-------------------- b
While .equals() always compares value of String so it gives true in both cases
String a="Test";
String b="Test";
if(a.equals(b)) ===> true

String a="test";
String b=new String("test");
if(a.equals(b)) ===> true
So using .equals() is awalys better.

##############################################################
Disclaimer: The Best answers from stackoverflow.com has been listed here.

No comments:

Post a Comment