Friday

String literal && String pool


/*  String object created with using new() operator.
    This always create a new object in heap memory.
    At the below, object and object2 have different references.
*/
String object = new String("Eda"); 
String object2 = new String("Eda"); 
System.out.println(object == object2); // false

/* String object created with using String literal syntax.
   If an object exists in string pool then returns it. Otherwise, creates a new string object and puts into string pool.
   At the below, literal and literal2 have the same reference.
*/
String literal = "Eda";
String literal2 = "Eda";
System.out.println(literal == literal2); // true

NOTE: While comparing two string, we can't know which string parameter has created with new() or literal. So use always equals().

Strings which has created with literal syntax, is cached. This cache is known as "String pool".

If an object exists in string pool then returns it. Otherwise, creates a new string object and puts into string pool. This is called as "interning".
     Interning can be manually, as follows.
          -manually intern in Java 6 is not a good practice. Just because pool has a fixed memory.

String literal = "Eda";
String object = new String("Eda"); 
String internedObject = object.intern();
System.out.println(literal == internedObject); // true

Just before java 7, that cache was in PermGen space. With java 7, it is in heap space.
     permgen space >> has fixed size && can not expanded at runtime, you had to change JVM option(-XX:MaxPermSize=1G) && risk of getting OutOfMemory error.
     heap space >> unreferenced strings has removed from pool && it is garbage collected which means strings with no references  will gone.

There is more JVM options for pool sizing: (your pool size should be high enough)
-XX:StringTableSize=4901 //The default pool size is: 1009 to the Java7u40, after that 60013, alsa java 8 is the same. 
-XX:+PrintStringTableStatistics //print string pool usage statistics when the program finish execution

No comments:

Post a Comment