How many objects will be created in the following cases :
In first case a new memory space is allocated in the heap on the account of the "new" and also allocted in the pool on the account of "Everybrickmatters".
1) String s1 = new String ("Everybrickmatters");
2) String s2= "Everybrickmatters";
In second case s2="Eevrybrickmatters" is String literal . In order to store the string literals ,a String pool is created by the JVM . When a String literal is found in a class , it will be added to the string pool. However . if the same literal already exists in the pool then it uses the existing one in the pool , as string object is immutable .
In first case a new memory space is allocated in the heap on the account of the "new" and also allocted in the pool on the account of "Everybrickmatters".
In the second case , when the statement is being compiled , a pointer to the String literal "Everybrickmaatters " is stored in s2 . However if the same string had not been present , then it would have created a new instance in the pool and stored the reference .
See the following figure :
1) When String s1 = new String ("Everbrickmatters") will be compiled . The memory allocated will be in the following way :
2) When the Second statement String s2 = "Everybrickmatters"; , then a reference pointing to the string constant will be created. See the following figure :
Please comment if you like the above post or if you find any mistake.
No comments:
Post a Comment