Where are string values stored in memory ?
The location where the string values are stored in memory depends on how we create them.
Approach 1-In the example below we are directly referencing a String literal.
String str1 = "value";
This value will be stored in a "String constant pool" ? which is inside the Heap memory. If compiler finds a String literal,it checks if it exists in the pool. If it exists, it is reused.
String str5 = "value";
In above example, when str5 is created - the existing value from String Constant Pool is reused.
Approach 2-However, if new operator is used to create string object, the new object is created on the heap. There will not be any reuse of values.
//String Object - created on the heap
String str2 = new String("value");
No Comments Yet!!