DEV Community

Marcos Gabriel de Oliveira Favaretto
Marcos Gabriel de Oliveira Favaretto

Posted on

Strings in Java are immutable, once declared they cannot be changed.

String Pool

Strings in Java are immutable. It means that its value once declared cannot be changed anymore. The String variables just stores references to the String value on Heap memory, and it can be changed, like we used to do during the execution of our program.

When a literal String is declared, it is saved on a specific local of the Heap memory: the String Pool.

To clarify it better, let's declare a new String variable on our Java class.

public class Application {
    public static void main(String[] args) {
        String myFirstString = "Hello";
    }
}
Enter fullscreen mode Exit fullscreen mode

When we declare a String variable and initialize it with the literal way, that is what happen at the memory allocated to our application.

Line1

Declaring another String variable using the same literal attribution, another local on String Pool won't be created, since the JVM knows that there already exists a String value declared as Hello.

Code

public class Application {
    public static void main(String[] args) {
        String myFirstString = "Hello";
        String mySecondString = "Hello";
    }
}
Enter fullscreen mode Exit fullscreen mode

If we look at memory:

Line2

At the beginning, the String Pool is empty. After declaring the myFirstString, JVM looks inside it and search for the value "Hello". If it still doesn't exist, JVM stores that value and return the address. If already exists, returns the address of the value.

To make sure that myFirstString and mySecondString are appointing to the same local of memory, we can compare them with the == operator, which returns true if they have the same address.

Code

public class Application {
    public static void main(String[] args) {
        String myFirstString = "Hello";
        String mySecondString = "Hello";

        System.out.println("Has same address: " + (myFirstString == mySecondString));
    }
}
Enter fullscreen mode Exit fullscreen mode

Result

Has same address: true
Enter fullscreen mode Exit fullscreen mode

If we change both values, the Hello will not be removed from memory, it just will not have a pointer with its address, and another allocation on String Pool will be created, having the new declared value.

Code

public class Application {
    public static void main(String[] args) {
        String myFirstString = "Hello";
        String mySecondString = "Hello";

        myFirstString = "World";
        mySecondString = "World";

        System.out.println("Has same address: " + (myFirstString == mySecondString));
        System.out.println("Has same address as \"Hello\" value: " + (myFirstString == "Hello"));
    }
}
Enter fullscreen mode Exit fullscreen mode

Result

Has same address: true
Has same address as "Hello" value: false
Enter fullscreen mode Exit fullscreen mode

Memory Representation

Line3

There we can see the immutable propriety, since the value stored did not change after an alteration of variables's value attribution, and other local on String Pool was occupied with the new value.

It is important to say that if we declare a String variable with the new keyword, that value will not be created at String Pool, instead of it, will be saved at Heap Space every time a String is declared with the new keyword.

Code

public class Application {
    public static void main(String[] args) {
        String myLiteralString = "Hello";
        String myNewString = new String("Hello");

        System.out.println("Has same address: " + (myLiteralString == myNewString));
    }
}
Enter fullscreen mode Exit fullscreen mode

Result

Has same address: false
Enter fullscreen mode Exit fullscreen mode

Memory Representation

Line4

To allocate that value on String Pool, we can manually use the String.intern() method.

Code

public class Application {
    public static void main(String[] args) {
        String myLiteralString = "Hello";
        String myNewString = new String("Hello");

        System.out.println("Has same address: " + (myLiteralString == myNewString));

        myNewString = myNewString.intern();
        System.out.println("Has same address after intern: " + (myLiteralString == myNewString));
    }
}
Enter fullscreen mode Exit fullscreen mode

Result

Has same address: false
Has same address after intern: true
Enter fullscreen mode Exit fullscreen mode

Memory Representation

Line5

Advantages

  • The use of String Pool improves the performance of our application, since it works as a cache, allowing the JVM to also spend less memory.
  • Allows reusability of String values.
  • Allows more security for Strings that cannot be change during the execution of our project (like passwords).

Disadvantages

  • Every time a String is changed, another value will be allocated in memory, and the old value will be still existing, using unnecessary space. When working with some String variable that changes a lot, that can be a memory problem.

It is possible to use Strings on a mutable way through Java StringBuilders. Using that resource, the String value will not be stored on String Pool and the allocated value will be changed at the same address, not being reallocated.

Of course, we can have some cases that Immutable Strings cannot solve our problem, and be a problem of performance. You need to understand your case for the best application.

That topic about String Pool is based on Scaler, Baeldung, Coding with John and Vogella.

That's all ;D
Please any feedbacks, improvements or revisions are welcome.

Top comments (2)

Collapse
 
vineetjadav73 profile image
vineetjadav

Extremely valuable information as their values cannot be altered after creation. This design choice ensures string integrity and promotes stability in Java programs. It is necessary to learn the accurate and comprehensive knowledge when it comes Java. Do check out Java Programming Courses to excel in your coding career.

Collapse
 
marcosgofavaretto profile image
Marcos Gabriel de Oliveira Favaretto

Thanks for feedback. I changed about thread safe 🙏🏻