Simple string query that confuses me
I'm new to Java and want to know the logic behind this question as asked by a friend.
Say the row pool is empty and
the programmer performs
String str = new String("Raj");
How many objects will be created because of this.
My friend said that 3 objects will be created but doesn't know the logic.
Can anyone guide me how 3 objects will be created.
Two string objects are created: one is the string literal "Raj" and one is the intermediate String object created new String(...)
.
It could be argued that there is another (third) object that is char[]
in the inner strings of a String literal, which you can also count, is an object, but not a String object. (Newline will use the same char[]
and won't create a new one)
EDIT . Pointed by @jdphenix, every object created is also a subclass Object
and therefore contains an instance of it (you can pass it to an object and use it as such). So, technically, there are actually over 3 objects created here, but only 2 of them are String objects.
In reality, two objects are created.
"Raj"
and
new String("Raj");
Your friend is either unfaithful or ... imposing on you.
Excuse me.
Edit . As correctly stated, a third object is created, which is the object char[]
in the interior String
.
It will be created 2 objects (a string literal "Raj"
and object String
: new String("Raj")
)
but only one String
will be interned and placed in the internal pool String
(string literal).
Now I'm confused ... as I know ... intern () is a method that creates a string literal in a string pool. what in this case
String str = new String ("Raj");
str.intern (); // this will add Raj to the string pool; or my understanding is wrong. Every time I create a String object, the string literal will be created in the string pool if it doesn't already exist.
First, when this code is executed, the pool will already be full, so your assumption that the row pool is empty is wrong.
One string object will be in the pool for the "Raj" string constant.
The string object will be created.
There are only 2 objects in all, and only 1 object crashed as a result of this code being excited.