Strings can be defined in Java in two ways.
1. String Literals
2 Traditional way(using 'new' operator)
String Literals
If a String is created by using String literal notation, memory will be allocated directly in string pool.
String pool is subset of Heap memory (Where objects will be created).
e.g. String companyName = "Surimenus";
String empName= "Bhargav";
Using 'New' Operator
If a String is created using new operator, memory will be allocated in Heap Memory not in String pool.
e.g.
String companyName = new String("Surimenus");
String empName= new String("Bhargav");
String Pool vs Using 'new' Operator
String which are created in String pool will re-reference by reference which contains the same content.
For example consider the following.
String cn1 = "Surimenu";
String cn2 = "Surimenu";
In the above scenario cn1 and cn2 references having the same content and these are created in String Pool. So for only one Object memory will be allocated for the two references (cn1 and cn2)
For suppose if you create String Objects as follows.
String cn1 = new String("Surimenu");
String cn2 = new String("Surimenu");
In the above scenario cn1 and cn2 references having the same content and these are created in Heap memory. So memory will be allocated for two Objects for two references (cn1 and cn2).
1. String Literals
2 Traditional way(using 'new' operator)
String Literals
If a String is created by using String literal notation, memory will be allocated directly in string pool.
String pool is subset of Heap memory (Where objects will be created).
e.g. String companyName = "Surimenus";
String empName= "Bhargav";
Using 'New' Operator
If a String is created using new operator, memory will be allocated in Heap Memory not in String pool.
e.g.
String companyName = new String("Surimenus");
String empName= new String("Bhargav");
String Pool vs Using 'new' Operator
String which are created in String pool will re-reference by reference which contains the same content.
For example consider the following.
String cn1 = "Surimenu";
String cn2 = "Surimenu";
In the above scenario cn1 and cn2 references having the same content and these are created in String Pool. So for only one Object memory will be allocated for the two references (cn1 and cn2)
For suppose if you create String Objects as follows.
String cn1 = new String("Surimenu");
String cn2 = new String("Surimenu");
In the above scenario cn1 and cn2 references having the same content and these are created in Heap memory. So memory will be allocated for two Objects for two references (cn1 and cn2).
Comments
Post a Comment