String in Java

108 views.

String is a predefined class, which can be used for storing a group of characters.

To store a group of characters we need to create an object of string class. The String class object can be created in two ways.

  • The string class object can be created by using new operator

String str=new String(“Hello”);

  • The String class object can be created by specifying a group of characters enclosed directly in pair of double quotes(” “).

String str=”hello”;

The String objects created by both mechanisms are called as immutable object, which means once the String object is created we can not modify the content of the object.

Difference between the two mechanisms of creating String objects:

String Object Created by using new Operator:

  • Location:

The String objects created by using new operator are stored in heap memory.

  • Allocation:

If the String objects are stored in heap memory then, it will never verify, whether the heap memory contains with same content or not, it will always create new object and store the content.

 

Unreferenced Object:

If an object does not have any live reference i.e. no reference variable is reference to the object then, the object should be called as unreferenced object.

  • Deallocation:

If the heap memory contains unreferenced object then, they will be deallocated by garbage collector.

String object created by specifying a group of characters enclosed directly in Pair of double quotes

  • Location

If a String object is created by enclosing a group of chaacters in a pair of double quotes(” “) then, they are stored in string constant pool.

  • Allocation:

If the String objects are stored in string constant pool then, it will always verify whether the string constant pool contain objects with same content or not if available then, refer to existing object. If not available then create a new object.

String s1=”hi”;

s1=”bye”;

String s2=”bye”;

  • Deallocation:

If the string constant pool contains unreferenced object then, they will be deallocated by the string pool if  itself, when the string constant pool completely filled.

If a String object is created by using new operator then the content will be stored in both heap and string constant pool but the reference will refer to the object available in heap memory.

String s1=new String(“heelo”);

 

If a String object is created by specifying a group of characters enclosed directly in a pair of double quotes then the content will be stored in only string constant pool.

String s1=”hello”;

Leave a Reply