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.

4
  • 1
    There are two objects. Commented Nov 19, 2017 at 7:04
  • Also: stackoverflow.com/questions/15324143/… Commented Nov 19, 2017 at 7:04
  • @alfasin The question you are referring is different. Please go through the question. Though the Answer covers both. Does that make a duplicate? Commented Nov 19, 2017 at 7:13
  • @alfasin Both answers in the proposed duplicate are extremely poor quality. VTR. Commented Nov 19, 2017 at 9:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Object is created by compiler or JVM?
-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.

5 Comments

Usual mistake. All strong literals are already in the pool when this code executes.
@EJP as mentioned - i read this on the link (above) - journaldev.com/797/what-is-java-string-pool.
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.
good to know... will keep this in mind (Y)
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.