Thursday, 28 April 2011

How Many String Objects Are Created ?

Consider the code fragment shown below:

String s1="abc";
String s2="def"
System.out.println(s1 + " " + s2);


The question is how many String objects are created after the last line is compiled by Java.

To solve questions like this one can use Eclipse decompiler (JAD) to see how the Java compiler actually interpreted that third line.

1) For  any java developer it will be very easy to tell that first two lines create one object each and hence two objects in first two line.

2) The third line in the above code is interpreted by JDK 1.5 compiler as:
system.out.println((new StringBuilder(string.valueOf(s1))).append(" ").append(s2).toString());

This clearly tells us that 2 more string objects (" " and "abc def") are created in the last line.
3) Hence we can say that 4 String and 1 String Builder objects are created by that piece of code.

So the following code shows it all:
string s1 = "abc";
string s2 = "def";
system.out.println((new StringBuilder(string.valueOf(s1))).append(" ").append(s2).toString());

No comments:

Post a Comment