This is a question from Valiveru's exam. How many String objects are created when we run the following code. String s1,s2,s3,s4; s1 = "Hello"; //line 1 s2 = s1; //line 2 s3 = s2 + "Pal";//line 3 s4 = s3; //line 4 A.1 B.2 C.3 D.4 E.We can't say. The ans given is c (ie 3 objects) . My answer was b(2 objects)
I would say that at line 1 and 3 objects are created. At line 2, s2 points to an already cretaed object and at line 4 s4 points to an already cretaed object line 3. Am I right?
well the answer given is rite. 3 objects r created. on line 1 one object is created on line 2 the reference to that object is assigned to s2 on line 3 an object with the value "Pal" is created which has no reference. then the strings r concatenated and a 3rd string object "HelloPal" is created on the 4th line the reference to this new object is assigned to s4 [ December 07, 2003: Message edited by: Mohit Goyal ] [ December 07, 2003: Message edited by: Mohit Goyal ]
According to me, only 2 objects are created in the above program.I called the method hashCode()from object class on every string object created.The output would have been three different hashcodes for each created object it there had been 3 objects created. But, if you see the output,you will see just the two objects i.e.only two hashcodes. (I am sorry something went wrong in the cut and paste) Please see the output for ypurself, just to crosscheck!