• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Doubt in String's

 
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear all
i had attened one interview yesterday there the asked me the question below...

String s="abc";
if(s.equals("abc"))
{
}
if("abc".equals(s))
{
}

what is the difference between both the condition...he has given me one hint that under one condition they will differ
 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For this particular example, there is absolutely no difference.

In the general case (assuming you don't know what value String s holds), think about what happens in each case if s == null
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
D. Ogranos is right. Assume s is null.
throws NullPointerException

but


will never throw because you know that Left Hand Side string at the compile time itself that it can not be null. And putting a '.' operator on a non-null object will always let your program go smoothly without exceptions.

Else you would be required to code like this:


which unnecessarily brings in another && condition. Ofcourse, there could be tradeoffs if one could not easily understand why you have used "abc".equals(..) instead of the other approach.
 
If you like strawberry rhubarb pie, try blueberry rhubarb (bluebarb) pie. And try this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic