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";
  • possible duplicate of [How many Java objects are generated by this - new String("abcd")](http://stackoverflow.com/questions/5192574/how-many-java-objects-are-generated-by-this-new-stringabcd) – Hot Licks Aug 10 '14 at 03:09

5 Answers5

3

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

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

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

Macrosoft-Dev
  • 2,195
  • 1
  • 12
  • 15
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.

veeru
  • 26
  • 2
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?

Community
  • 1
  • 1
eckes
  • 10,103
  • 1
  • 59
  • 71
-1

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

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • But it is present. The compiler and class loader put it there, before the statement was executed. – user207421 Mar 23 '17 at 05:49
  • @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 – TheLostMind Mar 23 '17 at 07:06