0

Possible Duplicate:
What is the difference between “text” and new String(“text”) in Java?

Please explain the brief and detailed difference between following 2 statements:

String a= "somevalue";
String b = new String("somevalue");

I know that 2nd statement creates and provide memory to String Object b in heap. But why object a doesn't get memory and its still allowed to operate on string methods.

Community
  • 1
  • 1
Arun Kumar
  • 6,534
  • 13
  • 40
  • 67

2 Answers2

3

a and b are references to Objects, not Objects.

When you do a = b; it doesn't copy the Object, it copies a reference to an Object.

A String has a char[] inside it which is another object.

a gets an reference to an existing object so it may not need any extra memory.

b get a reference to a newly created object so that requires more memory.

its still allowed to operate on string methods.

This has nothing to do with how the object was created.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    thank you @Peter. i want to add something. You should use `a` if you know object before creating, but use `b` in opposite case. – Dmitry Zagorulkin Sep 06 '12 at 09:45
  • 1
    @ZagorulkinDmitry: b should NEVER be used. It makes no sense to create a copy of an immutable object. It only wastes memory and CPU cycles. – JB Nizet Sep 06 '12 at 13:46
  • @JBNizet Unless the `char[]` which backs the String is excessive in which case you need to take a copy of the bit you want. ;) – Peter Lawrey Sep 06 '12 at 13:54
3

The first affects the literal String object "somvalue" to variable a. This literal String object is cached in a pool, as all literal Strings.

The second creates a new instance of empty String. Since String instances are immutable, it's equivalent to String b = "";, except it instantiates a new object for nothing.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255