Reputation: 90
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";
Upvotes: 1
Views: 133
Reputation: 10433
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?
Upvotes: 0
Reputation: 26
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.
Upvotes: 1
Reputation: 32488
Only one String literal will be created in the String constant Pool.
Upvotes: 3
Reputation: 36304
One String Object (Literals are also Objects) is created IF "Hello" is NOT already present in the String pool.
Upvotes: -1
Reputation: 2185
No object is created but rather value is inserted in String pool if it is inserted before
Upvotes: 3