-2

i create a string object using assignment operator

String nameVar = "Henry";
(Which makes a object in String pool/Constant pool with value of Henry)

Then i assign again a new value to variable nameVar.

nameVar = "Ann";
(Which makes a object in String/Constant pool with value "Ann" and new reference address is stored in variable)

My problems..
1.Problem is after assigning second object to variable does previous object is discarded or store in pool?

2.if it is stored in pool. i create a another new variable and create a string object with value "Henry" using assignment operator does it refer to same object that stored in pool?;

String newNameVar = "Henry";

3.i create a String object using new operator with a value "Britney" then i create another string variable(Object) using new operator with same value "Britney". does second variable refer to previous object or just create a new object and refer to it?

String oldVar = new String("Britney");
String newVar = new String("Britney");

cheers.

paul
  • 37
  • 4

2 Answers2

0

Every time you write a string with "..." it is either reused if the same string exists in string pool or new is created in string pool.

And new keyword always creates new object on the heap.

It's all very well explained in book Sun Sertified Java Developer 6 by Kathy Sierra.

Volodymyr Levytskyi
  • 3,364
  • 9
  • 46
  • 83
0

Java maintains string object in pool and head. Whenever you use assigment by using quote "someString", java first checks in pool if this string exists, if yes, it refers to same other wise it creates new string object in memory.

In case of new operator, new String("abc") , it creates object in heap. Irrespective of whether head alreay has object or not.

Until and unless, you have some explicit requriment, prefer to use "some" instead of new keyword. It will help you in memory management.

Panther
  • 3,312
  • 9
  • 27
  • 50