i was wonder which is what

I was asked in an interview a while ago which is more efficient and i had no clue, just out of curiosity anyone know the difference...

String x = "ben";

"ben".equals(x);

x.equals( "ben" );

which is better? i though they were the same as far as creating new memory and what not. why is one better then the other and would i care if the java VM handles memory management

[399 byte] By [bens2333a] at [2007-11-27 3:53:46]
# 1
The first is better in that it can't throw a null pointer exception.That's it.
paulcwa at 2007-7-12 8:57:50 > top of Java-index,Java Essentials,Java Programming...
# 2
I wish I'd been asked that in an interview. I'd be asking the guy where he thought efficiency figured in the situation
georgemca at 2007-7-12 8:57:50 > top of Java-index,Java Essentials,Java Programming...
# 3
> The first is better in that it can't throw a null> pointer exception.> That's it.And the second is subjectively better in that it looks more natural.I go with foo.equals("bar") whenever there's a precondition that foo not be null.
jverda at 2007-7-12 8:57:50 > top of Java-index,Java Essentials,Java Programming...
# 4
> The first is better in that it can't throw a null> pointer exception.> That's it.In that particular code, neither one can throw NPE. :-)
jverda at 2007-7-12 8:57:50 > top of Java-index,Java Essentials,Java Programming...
# 5
For that matter, I'm generally suspicious of any code that does string comparisons, unless it's a sort or a parser. I've seen too much code that hides semantics in naming schemes...
paulcwa at 2007-7-12 8:57:50 > top of Java-index,Java Essentials,Java Programming...
# 6

> For that matter, I'm generally suspicious of any code

> that does string comparisons, unless it's a sort or a

> parser. I've seen too much code that hides semantics

> in naming schemes...

Not to mention the over-use of String as a catch-all datatype. "Oh, we've used Strings here to represent the status of the order". Why? Why not have a Status class? etc

georgemca at 2007-7-12 8:57:50 > top of Java-index,Java Essentials,Java Programming...