How many string objects will be created by the following code?
String s = "Mahendra" + "Singh" + "Dhoni";
Will it create 4 string objects in the string pool or will it create more than that? Please explain in detail.
P.S. I have seen other examples and they deal only for 2 string objects.
EDIT : I see from the answers that in above case only 1 object will be created. Thanks a lot for some very good suggestions. Sorry to ask a stupid question but can you please tell in the below case how many objects will be created?
String s = "Mahendra";
s = s + "Singh" + "Dhoni";
2nd EDIT : Sorry again but I still have some doubt. I see in the comments that in the above case 3 objects will be created "Mahendra", "SinghDhoni" and "MahendraSinghDhoni". My doubt is shouldn't it be calculated from the left to right. Am I missing something - concept wise? Please help.
Also, in another case, if I twist this question, how will the number of objects change. I am asking this as in detail to clear it for lot of my colleagues as well. All the help is appreciated.
String s = "Singh";
s = "Mahendra" + s + "Dhoni";
If your code was :
public static void main(String[] args) {
String s = "Mahendra" + "Singh" + "Dhoni";
System.out.println(s);
}
Look at the byte code :
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=2, args_size=1
0: ldc #16 // String MahendraSinghDhoni --> This line
2: astore_1
3: getstatic #18 // Field java/lang/System.out:Ljav
/io/PrintStream;
6: aload_1
7: invokevirtual #24 // Method java/io/PrintStream.prin
ln:(Ljava/lang/String;)V
10: return
As you see the compiler is adding All three strings during compile time. So there will be only one string on the String constants pool thats all.
EDIT : based on the edited question :
"Singh" + "Dhoni"
will be added during compile time. So there will be totally 3 String objects.
"Mahendra"
and "SinghDhoni"
will be on String constants pool and then
mahendraSinghDhoni
will be on heap.
This will create only 1 string s in string pool. Please read the difference bwt String object and literal it will help you understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With