Saturday, November 16, 2024
Google search engine
HomeData Modelling & AIWhy Java Strings are Immutable?

Why Java Strings are Immutable?

Before proceeding further with the fuss of immutability, let’s just take a look into the String class and its functionality a little before coming to any conclusion. In this article, we will learn about the fact why Java Strings are Immutable.

What are Immutable objects?

Immutable objects are objects which once declared elements can’t be modified after it.

How are String Immutable?

A String in Java that is specified as immutable, as the content shared storage in a single pool to minimize creating a copy of the same value. String class and all wrapper classes in Java that include Boolean, Character, Byte, Short, Integer, Long, Float, and Double are immutable. A user is free to create immutable classes of their own.

String declaration:

String str = "knowledge";

This, as usual, creates a string containing “knowledge” and assigns it to reference str. Simple enough? 

Let us perform some more functions:

// assigns a new reference to the 
// same string "knowledge"
String s = str;

Let’s see how the below statement works:

  str = str.concat(" base");

Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
    String str="Knowledge";
      String s=str;
      str=str.concat(" Base");
      System.out.println(str);
    }
}


Output

Knowledge Base

This appends a string ” base” to str. But wait, how is this possible, since String objects are immutable? Well to your surprise, it is.

When the above statement is executed, the VM takes the value of String str, i.e. “knowledge” and appends ” base”, giving us the value “knowledge base”. Now, since Strings are immutable, the VM can’t assign this value to str, so it creates a new String object, gives it a value “knowledge base”, and gives it reference str.

An important point to note here is that, while the String object is immutable, its reference variable is not. So that’s why, in the above example, the reference was made to refer to a newly formed String object.

At this point in the example above, we have two String objects: the first one we created with the value “knowledge”, pointed to by s, and the second one “knowledge base”, pointed to by str. But, technically, we have three String objects, the third one being the literal “base” in the concat statement.

Why Java Strings are immutable in nature?

These are some more reasons for making String immutable in Java. These are:

  • The String pool cannot be possible if String is not immutable in Java. A lot of heap space is saved by JRE. The same string variable can be referred to by more than one string variable in the pool. String interning can also not be possible if the String would not be immutable.
  • If we don’t make the String immutable, it will pose a serious security threat to the application. For example, database usernames, and passwords are passed as strings to receive database connections. The socket programming host and port descriptions are also passed as strings. The String is immutable, so its value cannot be changed. If the String doesn’t remain immutable, any hacker can cause a security issue in the application by changing the reference value.
  • The String is safe for multithreading because of its immutableness. Different threads can access a single “String instance”. It removes the synchronization for thread safety because we make strings thread-safe implicitly.
  • Immutability gives the security of loading the correct class by Classloader. For example, suppose we have an instance where we try to load java.sql.Connection class but the changes in the referenced value to the myhacked.The connection class does unwanted things to our database.

Important Facts about String and Memory Usage

What if we didn’t have another reference s to “knowledge”? We would have lost that String. However, it still would have existed but would be considered lost due to having no references. 
Look at one more example below

Example

The below programs demonstrate the immutability of Java strings.

Java




// Java Program to demonstrate why
// Java Strings are immutable
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String s1 = "java";
        s1.concat(" rules");
 
        // Yes, s1 still refers to "java"
        System.out.println("s1 refers to " + s1);
    }
}


Output

s1 refers to java

Explanation of the above method

  1. The first line is pretty straightforward: create a new String “java” and refer s1 to it.
  2. Next, the VM creates another new String “java rules”, but nothing refers to it. So, the second String is instantly lost. We can’t reach it.

The reference variable s1 still refers to the original string “java”.

Frequently Asked Questions (FAQs)

Q1: Where do these String objects go? 

Answer:

Well, these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.As applications grow, it’s very common for String literals to occupy a large area of memory, which can even cause redundancy. So, in order to make Java more efficient, the JVM sets aside a special area of memory called the “String constant pool”.When the compiler sees a String literal, it looks for the String in the pool. If a match is found, the reference to the new literal is directed to the existing String and no new String object is created. The existing String simply has one more reference. Here comes the point of making String objects immutable:

In the String constant pool, a String object is likely to have one or many references. If several references point to the same String without even knowing it, it would be bad if one of the references modified that String value. That’s why String objects are immutable.

Q2: What happens if someone overrides the functionality of the String class? 

Answer:

As String class is marked final so that nobody can override the behavior of its methods.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments