Pages

Monday 18 May 2015

String Object Creation and Memory Management_String_2


Memory Management:

   Before dealing with String object creation, let us understand how memory is managed when handling String. The memory division is as shown in below image.


        




  String constant pool is a special memory which is used to store string objects.


String Object Creation:

  • By new keyword:


                   The new keyword will create a new String object and the object is placed in heap memory. Every time you use new keyword to create string object, each time JVM creates a new object and allocates memory.


     
         Given below is the code fragment creating a String object using new keyword. 


 String str1=new String("JAVA");






In the above code fragment a new string object is created and placed in heap memory, the string literal “JAVA” is placed in string constant pool and the variable ‘str’ refers to the memory location of string object.


  • By String Literal:



     The variable of type string is assigned directly with string literal using double quotes as shown below in the code fragment.



String str2="JAVA";



                  In the above code fragment the “JAVA” is String literal and str2 is variable of type string.


How String Literal way of string creation works?


       When you create a string literal like in the above code fragment, the JVM checks the string constant pool and scans for the match of string literal mentioned by you. If the string literal is already present in string constant pool then JVM simply returns the reference to the string literal already present in the string constant pool. If JVM doesn’t find any match for string literal mentioned then it creates a new string instance and places it in string constant pool.