-> There is string pool in java which is used for managing the memory efficiently and save the money invested in the memory.
-> There are two types of declaring strings in java:
String Literal
String Object.
Example:
String s="ABC"; //String Literal
String s1="ABC"; //String Literal
String sq=new String("ABC"); //String Object
String sq1=new String("ABC"); //String Object
Both stm are use to create string object in java.
**
When we use String s="Abc" then string object will be created in the string constant pool SCP area. it is one of memory in method area.
when String literal is created in java, JVM checks the string pool if the string content is already present then again memory is not allocated.
So, It optimizes the use of memory.
String sq1=new String("ABC");
======
But this is not true of u create a string using Option 2. Then the String object is created on heap and each time you create a string object, a new object is created irrespective of its content.
So, same thing is not applies to String objects. String objects shown in example sq and sq1 occupy different location in memory.
****** Below are the hard requirements of an immutable object.
Make the class final
make all members final, set them explicitly, in a static block, or in the constructor
Make all members private
No Methods that modify state
Be extremely careful to limit access to mutable members(remember the field may be final but the object can still be mutable. ie private final Date imStillMutable). You should make defensive copies in these cases.
-> There are two types of declaring strings in java:
String Literal
String Object.
Example:
String s="ABC"; //String Literal
String s1="ABC"; //String Literal
String sq=new String("ABC"); //String Object
String sq1=new String("ABC"); //String Object
Both stm are use to create string object in java.
**
When we use String s="Abc" then string object will be created in the string constant pool SCP area. it is one of memory in method area.
when String literal is created in java, JVM checks the string pool if the string content is already present then again memory is not allocated.
So, It optimizes the use of memory.
String sq1=new String("ABC");
======
But this is not true of u create a string using Option 2. Then the String object is created on heap and each time you create a string object, a new object is created irrespective of its content.
So, same thing is not applies to String objects. String objects shown in example sq and sq1 occupy different location in memory.
****** Below are the hard requirements of an immutable object.
Make the class final
make all members final, set them explicitly, in a static block, or in the constructor
Make all members private
No Methods that modify state
Be extremely careful to limit access to mutable members(remember the field may be final but the object can still be mutable. ie private final Date imStillMutable). You should make defensive copies in these cases.
Comments
Post a Comment