Difference between String literal and String object

Published by

on

There are two different ways to express String in Java,

first one is to use String literal like

String str = "Hello World";

and the other one is to use String object like

String str = new String("Hello World");

String literal vs String object

Creating a String object with new(), it always creates a new object in heap memory where all the objects are stored.
However, creating an object with String literal is likely to return an existing object from String pool which is a cache of String objects on the heap area.

String pool

As seen from the above codes, String literal shows they refer to the same object while the new()objects are not.

Due to this difference, on memory perspective, it is recommended to use String literal when possible rather than the new() objects.

String Pool

  • String Pool is made up of a HashMap which is like the screenshot above.
    • The key is based on a hash function of the string.
    • Each row is called as a bucket.
  • When we provide a String key, it’ll look for the bucket according to the hash function, and then it’ll go through the list of String inside the bucket.
    • Which means the smaller the bucket size is, the faster it’ll iterate.
  • Using -XX:+PrintStringTableStatistics provides detail about the String Pool.

Tuning the String Pool

Let’s create an example for tuning the String Pool.

  • By default, the number of String Pool buckets will be 60013
  • Average bucket size: 16.676
  • Maximum bucket size: 30

If we double up the number of String buckets by using -XX:StringTableSize,

  • The number of String Pool buckets: 120121
  • Average bucket size: 8.331
  • Maximum bucket size: 40

As seen from the results, the Average bucket size is decreased to almost half size, which means it’ll take less time for searching the value from the String Pool HashMap.

Reference

One response to “Difference between String literal and String object”

Leave a comment