• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question on String comparision?

 
Ranch Hand
Posts: 558
2
Hibernate Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.

 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The first one avoids the possibility of a NullPointerException if str1 is null.
With the second one you should always check for null first
 
Kumar Raja
Ranch Hand
Posts: 558
2
Hibernate Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ah right....

I should have done a minimal research on this
reply
    Bookmark Topic Watch Topic
  • New Topic