hi friends, I've found this question one of our mock exam paper when i see this ,i just stuk up how it'll be the answer please provide me any insights on this. 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. Ans:- c
1.s1 = "Hello"; // Object n pool 2.s2 = s1; 3.s3 = s2 + "Pal"; // since reference var involvs in concat opr,new String created. [ which implies one in heap, one in pool(since "HelloPal" doesn't exist earlier) will be created ]. 4.s4 = s3;
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. Ans:- c
"Hello" and "Pal" are string objects which are created in pool. s1 and s2 point to the same "Hello" object in pool whereas "HelloPal" is another object which is created during concatenation pointed by s3 and s4. Therefore total object in a pool is 3.
Remember whenever you use a different string in your program e.g. "pal" a pool object is created.