String Object creation in Java
String object can be created in two ways
1- Using String literal- String literals create the object in String constant pool.If the string is already present
in String Constant pool it refers same String instead of creating new object thus better memory utilization.
for example
String A="apple";
String B="apple";
A and B refers to the same object present in String Constant Pool.Only one object get created
2- Using new keyword-When we use the new keyword to create the String object each time the new object gets created in (non-pool)heap memory.
for example
String s=new String("apple");
Above line will create new object in heap memory(non-pool) and s will refer to same.
Intern-intern() is used to put String object in String pool. intern() method called automatically when we use String literals to put the object in String pool if it is not already present.However,In case of new keyword, we have to call this method explicitly when we want
to put the object in String pool.
For example in above case
A & B refers to the same object while s creates the new object in heap memory and refers the same.
If you want that s should also refer to the same object you can call s.intern().
Hope String object creation and intern() method is clear to you.
Give you suggestion in comments.If you like the post Share with your friends on social network.
1- Using String literal- String literals create the object in String constant pool.If the string is already present
in String Constant pool it refers same String instead of creating new object thus better memory utilization.
for example
String A="apple";
String B="apple";
A and B refers to the same object present in String Constant Pool.Only one object get created
2- Using new keyword-When we use the new keyword to create the String object each time the new object gets created in (non-pool)heap memory.
for example
String s=new String("apple");
Above line will create new object in heap memory(non-pool) and s will refer to same.
Intern-intern() is used to put String object in String pool. intern() method called automatically when we use String literals to put the object in String pool if it is not already present.However,In case of new keyword, we have to call this method explicitly when we want
to put the object in String pool.
For example in above case
A & B refers to the same object while s creates the new object in heap memory and refers the same.
If you want that s should also refer to the same object you can call s.intern().
Hope String object creation and intern() method is clear to you.
Give you suggestion in comments.If you like the post Share with your friends on social network.
String Object creation in Java
Reviewed by JavaInstance
on
11:19:00 AM
Rating:
No comments: