aspose file tools
The moose likes Java in General and the fly likes Question on String comparision? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Question on String comparision?" Watch "Question on String comparision?" New topic
Author

Question on String comparision?

Kumar Raja
Ranch Hand

Joined: Mar 18, 2010
Posts: 457

Hi All,

I have seen codes where the way Strings are compared is different, which is illustrated below. I'm not sure which is a better approach.

For eg.

String str1="abc";

Now what is the difference between

"abc".equals(str1) and str1.equals("abc").

In either case, we are comparing two different objects. But which one is preferred over the other.

My lead was happy when I used "abc".equals(str1) but why? I was hesitant to ask him and may be there are some interesting things which everybody should know about this diff.


Regards
KumarRaja

Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3011
    
    9
The first one avoids the possibility of a NullPointerException if str1 is null.
With the second one you should always check for null first


Joanne
Kumar Raja
Ranch Hand

Joined: Mar 18, 2010
Posts: 457

Ah right....

I should have done a minimal research on this
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Question on String comparision?
 
Similar Threads
String comparison
String literal and String object comparison
equals() and ==, doubt
== and equals
String literal objects in String pool