How many String objects are created when we run the following code. String s1,s2,s3,s4; s1 = "Hello"; s2 = s1; s3 = s2 + "Pal"; s4 = s3; A.1 B.2 C.3 D.4 E.We can't say. I thought the answer is B, but the author says its C. Any suggestions ?
Hi Rajani, I think u r wrong and Viji's reply is correct. Lets see how it happens String s1,s2,s3,s4; s1 = "Hello"; ===> "Hello" created in String pool s2 = s1; **** The previous "Hello" is used here s3 = s2 + "Pal";===>"Pal" created in String pool then "HelloPal" is created s4 = s3; **** The previous "HelloPal" is used here Hope this is clear. Nissi
s1 belongs to the pool s2 doesn't create any string object because "Hello" is already in the pool. s3 doesn't belong to the pool but it is something like being created with keyword 'new' it id created somewhere in the memory so it is the second object which has been created s4 ref to the same object created by s3 so it is not a new object also it doesn't create a new string in the pool Answer is B.