Prashnikaप्रश्निका
Code
About
‹ Back to the paper

Question 47

1 mark

Computer ScienceISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024)Short answerArrays, Strings

Answer the following question.

String s1 = "Gujarat"; String s2 = new String("Gujarat"); String s3 = new String("Gujarat"); String…

String s1 = "Gujarat"; 
String s2 = new String("Gujarat"); 
String s3 = new String("Gujarat"); 
String s4 = "Gujarat";
How many String objects are created in the above snippet? Justify your answer.

Answer

Answer

3 String objects are created. s1 = "Gujarat" is a literal, placed in the String constant pool. s4 = "Gujarat" is also a literal with the same content, so it reuses the same pooled object as s1 (no new object). s2 = new String("Gujarat") and s3 = new String("Gujarat") each use the new keyword, so each creates a separate new object in the heap, even though their content is the same. So in total: 1 (pool, shared by s1 and s4) + 1 (s2) + 1 (s3) = 3 objects.