This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Doubt in String's Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt in String Watch "Doubt in String New topic

Doubt in String's

santhosh.R gowda
Ranch Hand

Joined: Apr 06, 2009
Posts: 296
Dear all
i had attened one interview yesterday there the asked me the question below...

String s="abc";

what is the difference between both the condition...he has given me one hint that under one condition they will differ

Creativity is nothing but Breaking Rules
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
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
zahid zubair
Ranch Hand

Joined: Aug 29, 2009
Posts: 32
D. Ogranos is right. Assume s is null.
throws NullPointerException


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.
It is sorta covered in the JavaRanch Style Guide.
subject: Doubt in String's