PRASHNIKAप्रश्निका
‹ Back to the paper

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

Computer Science20251 markShort answer
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

AI
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.
Arrays, Strings

From ISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024), question 47.