Difference between String & new String

G

Guest

Hi..,

What is the difference between
String abc = "abc";

&

String abc = new String("abc");

I know its a very simple question, but i am a beginner.

T
 
R

rounner

nospam said:
Hi..,

What is the difference between
String abc = "abc";

&

String abc = new String("abc");

I know its a very simple question, but i am a beginner.

T

See http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

They are essentially equivalent but:

When using abc = "abc", the string may be "interned" (see intern on
that page). That means that to conserve resources:
abc = "abc"
abcd = "abc"
abc is pointing to the same thing as abcd. The intern stuff allows you
to manage how this is handled.
 
D

Drazen Gemic

nospam said:
Hi..,

What is the difference between
String abc = "abc";

&

String abc = new String("abc");

I know its a very simple question, but i am a beginner.

There is no difference, far as I know.

DG
 
E

EricF

There is no difference, far as I know.

DG

Actually there is a difference - though to a beginner, it may be subtle.

With the new operator, there will be a new object.

String abc1 = new String("abc");
String abc2 = new String("abc");
boolean b;
b = (abc1 == abc2); //false - they are 2 different objects
b = (abc1.equals(abc2)); //true, they have the same value

String abc3 = "abc";
String abc4 = "abc";
b = (abc1 == abc2); //typically this will be true. The compiler does some
//"magic" to create a new object. The actual code may look something like this

String tmp = new String("abc");
String abc3 = t;
String abc4 = t;

Eric
 
R

Roedy Green

There is no difference, far as I know.

new String has the side effect of wasting RAM and giving you a String
with a clone reference != to the original. Almost never do you want
that.
 
A

Adam Maass

EricF said:
Actually there is a difference - though to a beginner, it may be subtle.

With the new operator, there will be a new object.

String abc1 = new String("abc");
String abc2 = new String("abc");
boolean b;
b = (abc1 == abc2); //false - they are 2 different objects
b = (abc1.equals(abc2)); //true, they have the same value

String abc3 = "abc";
String abc4 = "abc";
b = (abc1 == abc2); //typically this will be true. The compiler does
some
//"magic" to create a new object.

*Always* will be true. A compiler or JVM that does not do this is not
compliant with the relevant specifications.

-- Adam Maass
 

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,270
Messages
2,571,102
Members
48,773
Latest member
Kaybee

Latest Threads

Top