Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Working with Strings 
2.1.
Syntax
3.
Why are Strings immutable in nature?
3.1.
Heap Space
3.2.
Security
3.3.
Thread Safe
3.4.
ClassLoader
4.
Facts regarding strings and memory usage
5.
Understanding the diagram
6.
Frequently Asked Questions
6.1.
What are the ways in which we can create a string object?
6.2.
What is the function of concat() in Java
7.
Conclusion
Last Updated: Mar 27, 2024

Immutable String in Java

Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Java is an object-oriented programming language that has many predefined data structures. Different data structures store different types of data like arrays are used to store homogenous elements at contiguous memory locations. One such data type in Java is String. Strings are used to store a sequence of char values. An array of characters works the same as a string. Arrays are of a fixed size that is, they are immutable therefore, strings are immutable as well. In this blog, we will discuss why strings in Java are immutable?

Also see, Duck Number in Java and Hashcode Method in Java.

Working with Strings 

Syntax

<String_type> <String_variable> = "sequence_of_string"


E.g

String string1 = "Hello";


The above example creates a string containing “Hello” and assigns it to reference string1.


The string class provides a large number of predefined functions that allow the programmer to manipulate strings. Some of the predefined functions are equals(), concat(), etc. 
 

String string2 = string1;
String2 = string2.concat("World");


The above statement creates a new string: string2, and appends a string “World” to it.

When the Java Virtual Machine executes the above statement, it takes the value of String string1, i.e., “Hello” and appends “World”, giving us the value “Hello World”. As Strings are immutable, the Java Virtual Machine can’t assign this value to string2, so it creates a new String object, assigns it the value “Hello World” and gives its reference to string2.

String Objects are immutable, but their reference variables are not. In the example above, we have three String objects: the first one being “Hello” which is pointed by string1, the second one being “Hello World” pointed by string2, and the third one being the literal “World” in the concat statement.

You can also read about the topic of Java Destructor and Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why are Strings immutable in nature?

Some of the reasons why Strings are immutable in Java are :

Heap Space

If Strings are not immutable, then the String pool and String interning won't be possible. Java Runtime Environment saves a large amount of heap space. The same string variable can be referred to by more than one string variable in the pool.

Security

If strings are not made immutable, then there will be a serious security threat to the application. For example, usernames and passwords are stored in Strings. Even the socket programming host and port description are passed as strings. Just because strings are immutable, their value cannot be changed. But if strings don't remain immutable, any hacker can cause a security issue in the application by changing the reference value.

Thread Safe

Multithreading is possible with strings because of their immutableness. Different threads can access a single “String Instance”. 

ClassLoader

Classloader uses string objects as an argument in Java. If the string object can be modified, its value can be changed, and because of this, the class that will be loaded will be different. To avoid such misinterpretation, strings are immutable.

Facts regarding strings and memory usage

Code  

import java.io.*;

class Example {
    public static void main(String[] args)
    {
        String string1 = "Hello";
        string1.concat("World");

        // Yes, string1 still refers to "Hello"
        System.out.println("string1 refers to " + string1);
    }
}


Output

string1 refers to Hello


Try it by yourself on online java compiler.

Explanation

We initially created a new String in the above code, “Hello” and string1 refers to it. Then the VM creates another new String, “Hello World”, but nothing refers to it. Because of this, the second String is lost and cannot be reached. The reference variable string1 still refers to the original string “Hello”. 


Every method except a few, which, when applied to a String object, creates a new String object. If no variable refers to it, then where do these String objects go? Such Strings exist in memory, and one of the key goals of any programming language is to make efficient use of memory. As the application grows in size, the string literals start occupying a large area of memory, which causes redundancy. Java Virtual Machine sets aside a special area of memory which is known as String Constant pool.

Whenever the compiler sees a String literal, it searches for that String in the pool. If a match is found, then the reference to that new literal is directed to the existing String. No new String object is created in such cases, and the existing String has one more reference.

In the String constant pool, a String object is likely to have more than one reference. If several references point to the same String without even knowing it, then it would be dangerous if any of the references modified that String value. This is why String objects are immutable.

Must Read Conditional Statements in Java

Understanding the diagram


 

  • When JVM executes the statement String string1=”Hello”, it will create a String object in the string constant pool and store “Hello” in it.
     
  • When the statement string2.concat(“World”) will be executed then, the JVM will create two new objects because we are trying to modify the original content.
     
  • Initially, for every String literal “World”, the JVM will create a copy of the string object in the string constant pool.
     
  • Then the second object will be created in the heap with the modified content “Hello World”. The string concatenation statement is executed at the runtime. Therefore if a new object is to be created, the object will always be created in the heap area and not in the string constant pool.
     
  • As this new object is not assigned to any reference variable, therefore it is known as an unreferenced object. The garbage collector will automatically remove this from memory.

Check out this article - C++ String Concatenation

Must Read Array of Objects in Java

Frequently Asked Questions

What are the ways in which we can create a string object?

There are two ways to create a String object: by using a String literal and by using a new keyword.
 

What is the function of concat() in Java

The string concat() method is used to concatenate the specified String at the end of the current String.

Conclusion

In this article, we have extensively discussed why strings are immutable in the Java programming language.

After reading about the immutability of strings in Java, are you not feeling excited to read/explore more articles on Strings? Don't worry; Coding Ninjas has you covered. To learn about special string functions in Java, strings in Java, and how to print all the permutations of a string.

Recommended Readings:

Recommended problems -

If you wish to enhance your skills in Data Structures and AlgorithmsCompetitive ProgrammingJavaScript, and many more, then you should check out our Guided path column at Coding Ninjas Studio. We at Coding Ninjas Studio organize many contests in which you can participate. You can also prepare for the contests and test your coding skills by giving the mock test series available. In case you have just started the learning process, and your dream is to crack major tech giants like Amazon, Microsoft, etc., then you should check out the most frequently asked problems and the interview experiences of your seniors that will surely help you in landing a job in your dream company. 

Do upvote if you find the blogs helpful.

Happy Learning!

Previous article
Strings in Java | Part 1
Next article
String Comparison
Live masterclass