dangerChihuahua007
dangerChihuahua007

Reputation: 20925

Why should I not instantiate a string object with a constructor?

In Java, apparently, String s = "foo" is preferred over String s = new String("foo").

Why? Isn't a new string object created in both cases? Why would the first case preclude calling a constructor?

Upvotes: 5

Views: 2959

Answers (4)

John Earles
John Earles

Reputation: 7194

Why? Isn't a new string object created in both cases?

No, the initial form being a string literal will be interned such that only one instance is created:

String s = "foo";
String s2 = "foo";

s == s2 => true

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346536

The first case is a string literal, simply a shorthand the language offers you to create a string. The String class constructor still gets called, just not explicitly, which means less typing and less code clutter.

The second case takes the String object already created by the literal and passes it to a constructor, which copies the content to create a new, separate String object. The literal will still be around because literals are interned.

There is rarely a point to using the String constructor (pretty much only when you've created a substring of a very large string and want to release the memory used by the rest of the string, because substrings by default use the same underlying char array as the original string, just with a different offset and length.

Upvotes: 4

Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

I don't think it's preferable. I assume the only "benefit" you get is that if you wrongfully use the "==" operator rather than the equals method, have two different instances of a string will fail faster which will prompt you to fix your code. (the == operator may "succeed" and fail unpredictably)

Unless of course your code requires you to construct two different instances for whatever reason

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272792

Why?

Because the second approach results in two string objects (the original due to the string literal, plus an explicit copy).

Upvotes: 9

Related Questions