Thursday, 2 February 2017

STRING POOLING IN JAVA

String pooling means grouping String objects. If we create objects by associating same literal, only one object is created and all reference variable are initialized with that same string object reference, then all reference variables are pointing to same string object. This is the reason why string object becomes immutable. It means to modify every time string data is not stored in same memory.

Since a string object is pointed by multiple referenced variables, if we change that string value using one referenced variable, all other referenced variables pointing to those objects are also affected. To solve this problem Sun decided to create string as immutable.

String pooling concept is not applicable for the string objects that are created using new keyword and constructor. They have separate object and those string objects are created in heap area directly.

String pooling is used to improve performance by saving memory.

Example –
public class String1 {
          public static void main(String[] args) {
                   String s1 ="abc";
                   String s2 ="abc";
                   String s3 = new String("abc");
                   String s4 = new String("abc");
                   System.out.println(s1==s2);
                   System.out.println(s1.equals(s2));
                   System.out.println(s3==s4);
                   System.out.println(s1==s3);
                   System.out.println(s3.equals(s4));
          }
}

Output –
true
true
false
false
true

No comments:

Post a Comment