Strings in Java - Immutablility , Interning and the String pool

0


Immutability

Strings in Java are immutable .An immutable object is one whose state cannot be modified once it is created . In Java , Strings are immutable . An interesting side-effect of the immutability of Strings is that methods like toLowerCase() in the String class doesn't affect the state of the original String , rather returns a new String.

Interning & The String pool

String interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. In Java , strings are interned using a String literal pool .

Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object is created and placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.

A side-effect of String interning in Java can be demonstrated by this code snippet.

String s1="aaaaa"; String s2="aaaaa"; System.out.println(s1==s2);

The above code snippet prints true because the two Strings are interned , and refers to the same pool instance.

Literal Strings , including those that can be computed by constant expressions at compile time are interned .
Strings explicitly created by the constructor or by concatenation at runtime are not interned.

The intern() method

The docs state When the intern method is invoked, if the pool already contains a
string equal to the String\ object as determined by
the method, then the string from the pool is
returned. Otherwise, the String object is added to the
pool and a reference to the String object is returned.
The below code snippet demonstrates the behaviour of the intern() method.


String s1 = "Zone817"; String s2 = new StringBuffer("Zone").append("817").toString(); String s3 = s2.intern(); System.out.println(s1 == s2);//prints false System.out.println(s1 == s3);//prints true

Read more »

0 comments:

Post a Comment

© Zone817. Powered by Blogger.