1

How many String objects are created in java by the following code: if there is no String object in the String pool containing the same value . (I read somewhere that Since we are passing arguments as "Hello", which is a String literal, it will also create another object as "Hello" on string pool. )

String s="Hello";
1

5 Answers 5

3

No object is created but rather value is inserted in String pool if it is inserted before

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

Comments

3

Only one String literal will be created in the String constant Pool.

Comments

1

Only one object will be created in the string constant pool. Reason behind is while we creating the object,we didn't use any "new" keyword.

Comments

0

You need to differentiate between literals which are loaded to the string pool when the class is loaded and passed around (this is your case) and the case of creating a string object by actually parsing/reading/constructing something.

The later case is of course much more often happening in programs, and it will always generate a new String object (even when the string value itself is already in the string pool).

See also Will the String passed from outside the java application be saved in String pool?

Comments

-1

One String Object (Literals are also Objects) is created IF "Hello" is NOT already present in the String pool.

2 Comments

But it is present. The compiler and class loader put it there, before the statement was executed.
@EJP - I said that it will be created if it is not present. Which means that it will not be created and added in String constants pool if it is present

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.