0

When we create a string using new operator, we place the string in double quotes inside the constructor.. Eg.

String s=new String("literal");

Does JVM creates a new string object for "literal" and pass it to the constructor? i.e, are two objects created one of which is garbage collected. Or, only one object is created which is referenced by s.

The question popped because of the following statement: Jvm creates object for "every double quoted" values in the program.

Deb
  • 5,163
  • 7
  • 30
  • 45

2 Answers2

0

Does JVM creates a new string object for "literal" and pass it to the constructor?

Essentially yes, although it is the compiler and classloader that are really responsible.

i.e, are two objects created one of which is garbage collected.

Yes, although I'm sure you mean 'collectable' rather than 'collected'.

Or, only one object is created which is referenced by s.

No.

Jvm creates object for "every double quoted" values in the program.

As stated, that is incorrect. Where did you read it? There is pooling to consider. There isn't a 1::1 relationship between string literals and objects.

user207421
  • 305,947
  • 44
  • 307
  • 483
-1

Found a pretty good explanation here: Link

String str = new String("Cat");

In above statement, either 1 or 2 string will be created.

If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool.

If there is no string literal “Cat” in the pool, then it will be first created in the pool and then in the heap space, so total 2 string objects will be created.

RangerReturn
  • 171
  • 3
  • 3
  • 18
  • Usual mistake. All strong literals are already in the pool when this code executes. – user207421 Nov 19 '17 at 09:31
  • @EJP as mentioned - i read this on the link (above) - https://www.journaldev.com/797/what-is-java-string-pool. – RangerReturn Nov 19 '17 at 09:34
  • I can see where you read it. It's still wrong. Show me something in the JLS or the JVM Specification that says so and you might have something. Anything else is just Internet junk. – user207421 Nov 19 '17 at 09:37
  • good to know... will keep this in mind (Y) – RangerReturn Nov 19 '17 at 09:39
  • For example, someone could quote your answer as fact, if left uncorrected. Or mine. These have no less and no more status than your link. Only the JLS and JVM Spec have status in this discussion. – user207421 Nov 19 '17 at 09:41