String is the very common class which every one is using frequently. Most of us aware that, String is an immutable object. As we already discussed that, for an each object memory will be allocated in heap memory area. But String objects are stored in a special memory area called "String Constant Pool" inside the heap memory area.
What is immutable object?
When state of an object can't be changed after the construction, those kind of objects are called immutable objects. For an example, all the wrapper classes are immutable objects.
String Constant Pool
All the String objects are stored in "String Constant Pool". As already discussed, "String Constant Pool" is a special memory area which is inside the heap memory. We will discuss how string objects are stored in "String Constant Pool".
When we create a new string object using string literal, that string literal is added into string pool, if the same string is not present already.
String str = "Hello";When we create an another string literal with same value, there will not be a new object for this. Instead of creating new object, reference of existing object will be return.
String str2 = "Hello";But if we try to modified the string object which is in String Constant pool, existing object will not be modified. Instead of modifying existing object, new object will be created and return the newly created string object's reference.
str2 = str2.concat("world");In above cases, we are creating String objects using String literal. But if we area creating String object using new keyword, that will be different. Because, all the string literals are stored in String Constant Pool and all the string literals are loaded into memory when class loading itself. But String objects which are created using new keyword will be stored in heap memory.
String str = "Hello"; String str2 = new String("Hello");
No comments:
Post a Comment