Data Scientist
Background Illustrations provided by:

Efficient way to create strings in Java ..

Strings are the most common datatype we use in any programming language. In Java, there are many ways we can create them. Before we know how to create them, we first need to understand how string memory is created internally in heap by JVM. Whenever a string is initialized, heap gives that particular string a memory reference in string pool. Stringpool is nothing but a pool which stores all the strings being used by program and is a subset of heap memory. This is very simple architecture to understand. 

    The catch is not where strings are stored but how they are stored. I will show you two common practices we follow.

A)  //Assigning a value to string variable

   String s1 = “Ravi”;

B)  // Using new Operator

   String s4 = new String(“Ravi”);

We all know Strings in Java are immutable which means once memory is assigned to a string it cannot be reassigned. Out of the two above methods, method A is preferred. Why? I will explain with a sample program. 


public class analyzeString {

String s1 = "Ravi";

String s2 = "Ravi";

String s3 = "Sourav";

String s4 = new String("Ravi");

public static void main(String args[])


     //Print values



In the above program string s1 is initialized to value ‘Ravi’. Here when I assigned s2 also to ‘Ravi’, it is not going to create another reference in string pool. s2 will also point to same memory location s1 is pointing to. In this way we are optimizing string pool saving extra bytes for s2. Now consider s4 which is initialized using operator new and assigned with same value ‘Ravi’. The catch here is it is not going to point to same location as s1 and s2. Operator ‘new’ will create another location in string pool. So, another instance is created with same value thus wasting memory. 

Thanks for reading and suggestions are most welcome.