how to compare two string in java?

0 votes
31 views
asked Apr 24, 2013 by arthi (1,110 points)
how to compare two string in java?

==  and .equals() which onw is best two compare the string?

1 Answer

0 votes
answered Apr 24, 2013 by admin (8,115 points)

 

== Compare Object refrence

.equal Compare 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 search for that literal in String pool , if it match, same referance 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") statement new String will be created in heap that referance 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 is awalys compare 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.

Hope this will help

...