Hi all This question was allready posted on this forum..but i could not find the satisfactory answer. so again posting it.... String s1 = "java";String s2 = "exam";System.out.println(s1 + " " + s2); How many String objects are created ? Thanks in advance
Munish Gulati<br />SCJP 1.4<br />Albert Einstein: There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.
Originally posted by Karan Gulati: String s1 = "java";String s2 = "exam";System.out.println(s1 + " " + s2); How many String objects are created ?
I'm not 100% on this, but I think the answer is actually 5. Obviously, "java", "exam", and (space) Strings are created - they're String literals. However, when you evaluate the expression in the println statement, you don't evaluate it all at once. Rather, you first evaluate s1 + " " to get the String "java " (so that's the 4th String) and then you perform the second concatenation to get "java exam" (which is the 5th String). If I'm mistaken, someone please correct me, but I believe the correct answer is 5.
I believe that there are 4 String objects: 1) There are 3 objects from the constant pool. (see lines 0, 3, & 20) 2) 1 temporary String object (line 29) Line 9 also shows that a StringBuffer is used to temporary contain the strings which is later converted to a String object using toString() method.
At least this is how my compiler does it. [ August 14, 2003: Message edited by: Alton Hernandez ]
posted 17 years ago
Alton brings up an excellent point. We don't REALLY know how many Strings are going to be created because the compiler may provide some optimizations, as was the case in his response. However, someone else's compiler might use my solution, which isn't as efficient. Regardless, don't expect to see this on the exam.
HI all, According to me, only 3 String objects will be created.. The concatenation is done using StringBuffer object.. so s1 + " " + s2 is not represented as String object rather it is a string BUffer object and then finally we have a String object.. All the concatenation operation done by compiler, uses StringBuffer. Please correct me, if i am wrong. Regards, Harry
Ok. So what's the right answer? 3/4. As Harry said that concatenation is done using string buffer and not the string objects and that's what the jdk1.4 api also says. So is the right answer 3? Thanks Deep