1

First i got a doubt that, when I create a string as

String s = new String("Stack");

whether "Stack" is saved in String Constant pool or not?

but this post : what happens with new String("") in String Constant pool tell that it is not.

but according to answers of this post : where do actual parameters in java store tell that it is present in Constant pool.

Please give a clarification on this.

Community
  • 1
  • 1

4 Answers4

4

If you do:

String s = "Stack";

.. then the literal string "Stack" is, in fact, a part of the constant string pool. When you do:

String s = new String("Stack");

... however, the original literal string "Stack" is a part of the string pool, but the use of "new" here forces a copy to be constructed that is not in the constant pool.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
2
String s=new String("Stack");

For the above statement, there will be a String literal Stack created in the constant pool, and in the heap, there will be another String object which will be referred by reference s.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
1

When you do something like this:

String a = "ang";

String b = "ang";

Both String a and b point to same "ang". Reference would be same because they both point to "ang" in string pool.

But when you do:

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

They both point to different objects.

Harsh
  • 1,665
  • 1
  • 10
  • 16
0

but this post : what happens with new String("") in String Constant pool tell that it is not.

No it doesn't. See the first comment: 'Both. Both. Both.' Or the accepted answer: "'intern()' or string literal".

but according to answers of this post : where do actual parameters in java store tell that it is present in Constant pool.

Correct. The compiler puts the string literals there, and intern() puts dynamic strings there.

user207421
  • 305,947
  • 44
  • 307
  • 483