why String s = new String("test") is bad?

S

Steve

I always wonder why String s = new String("test") is bad?

We always do String s = "test" instead. Why?

Please help explain. thanks!!
 
L

Lew

I always wonder why String s = new String("test") is bad?

We always do String s = "test" instead. Why?

Please help explain. thanks!!

How many copies of the same String contents do you really need?

The cited 'new' expression creates a copy of the String. It nearly
always adds no value and takes up both memory and time.
 
B

Bent C Dalager

I always wonder why String s = new String("test") is bad?

We always do String s = "test" instead. Why?

The former results in a string that is never from the string pool
while the latter may obtain a string from the string pool. The former
isn't necessarily "bad".

What /is/ bad is assuming all your strings are from the string pool
and that you can therefore compare them with "if (a==b)".

See also
http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()

Cheers,
Bent D
 
J

Juha Laiho

Steve said:
I always wonder why String s = new String("test") is bad?

We always do String s = "test" instead. Why?

With the former, you'll have two distinct String objects with
the same data. You'll have the static object (initialized by
the constant string "test", and you'll have another object
created as a duplicate of that static object, and you'll have
a reference to the latter stored in "s".

With the latter, you have one static String object with data
"test", and a reference to the static object stored in "s".


The issue is mostly that of memory consumption. A reference
is small, but an object is not. The space needed for 10000
copies of String object with data "test", and 10000 references
to those objects is surely greater than the space needed for
a single object and 10000 references. Similarly, it's an issue
of efficiency; setting a reference to point to an existing object
is a lot faster than creating a new object and setting a reference
to point to that new object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top