The Wayback Machine - https://web.archive.org/web/20240930165820/https://www.geeksforgeeks.org/java-string-is-immutable-what-exactly-is-the-meaning/
Open In App

Why Java Strings are Immutable?

Last Updated : 10 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 whose elements cannot be modified once declared.

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.



Previous Article
Next Article

Similar Reads

Immutable List in Java
ImmutableList, as suggested by the name, is a type of List which is immutable. It means that the content of the List are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the List, UnsupportedOperationException is thrown. An ImmutableList does not allow null element either. I
5 min read
Immutable Map in Java
ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only.If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown.An ImmutableMap does not allow null element either.If any at
6 min read
Collecting a Stream to an Immutable Collection in Java
Streams and Collectors were introduced in Java 8 introduced the concept of Streams. A Stream is a sequence, a sequence of objects. We generate Streams from input sources like Arrays, Lists, etc., and support aggregation operations like filter, map, limit, reduce, etc. We use Streams to pipeline data and ultimately collect it into some form of a Col
6 min read
Using Guava's Collectors for Collecting Streams to Immutable Collections in Java
Guava is a set of core libraries from Google that includes new collection types. For example, we multimap and multisets, immutable collections, a graph library, and utilities for concurrency. It is used by many companies. In this article, we are going to see how to use Guava's Collectors for Collecting Streams to Immutable Collections in Java. To u
3 min read
Primitive Wrapper Classes are Immutable in Java
In Java, an immutable class is a class (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) which once created then its body can not be changed and the same applies to immutable objects which once created cannot be changed. Now the question arises that we do need the help of wrapper classes while dealing with primitive data types in
3 min read
How to create Immutable class in Java?
Immutable class in java means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. We can create our own immutable class as well. Prior to going ahead do go through characteristics of immutability in order to have a good understanding while
3 min read
Factory method to create Immutable List in Java SE 9
Java 9 was released around march 2017 and In Java 9 there are some features are added in Java language and factory method for immutable List is one of them. Characteristics of Immutable List: As the name suggest these lists are immutable. If any attempt made to add, delete and update elements in the list we will have UnsupportedOperationException.
3 min read
Factory method to create Immutable Set in Java 9
Java 9 was released around march 2017 and please install jdk 9, it will be helpful in understanding the code used in this article. In Java 9, there are some features added in Java language and factory method for immutable Set is one of them. So lets get started! Characteristics of Immutable Set: As the name suggest these Set are immutable. If any a
3 min read
Factory method to create immutable Map in Java 9
In Java 9 there are some features are added in Java language and factory method for immutable map is one of them. Characteristics of immutable map: As the name suggest these map are immutable. If any attempt made to add, delete and update elements in the map we will have UnsupportedOperationException. Immutable map do not allow null element either.
3 min read
Why java.lang.VerifyError Occurs in Java and How to Solve this?
The Java Virtual Machine (JVM) distrusts all loaded bytecode as a core tenet of the Java Security Model. During runtime, the JVM will load .class files and attempt to link them together to form an executable — but the validity of these loaded .class files is unknown. To ensure that the loaded .class files do not pose a threat to the final executabl
6 min read
Number of common base strings for two strings
Given two strings s1 and s2, we need to find number of common base strings of two. A substring of a string s is called base string if repeated concatenation of the substring results in s. Examples: Input : s1 = "pqrspqrs" s2 = "pqrspqrspqrspqrs" Output : 2 The two common base strings are "pqrs" and "pqrspqrs". Input: s1 = "bbb" s2 = "bb" Output: 1
6 min read
Count of distinct Strings possible by swapping prefixes of pairs of Strings from the Array
Given an array string[] consisting of N numeric strings of length M, the task is to find the number of distinct strings that can be generated by selecting any two strings, say i and j from the array and swap all possible prefixes between them. Note: Since the answer can be very large, print modulo 1000000007. Examples: Input: N = 2 M = 3 string[] =
6 min read
Distinct strings such that they contains given strings as sub-sequences
Given two strings str1 and str2 of lengths M and N respectively. The task is to find all the distinct strings of length M + N such that the frequency of any character in the resultant string is equal to the sum of frequencies of the same character in the given strings and both the given strings are present as a sub-sequence in all the generated str
6 min read
Count of Palindrome Strings in given Array of strings
Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to return the count of all palindromic string in the array. Examples: Input: arr[] = {"abc","car","ada","racecar","cool"}Output: 2Explanation: "ada" and "racecar" are the two palindrome strings. Input: arr[] = {"def","aba"}Output: 1Exp
5 min read
Count of same length Strings that exists lexicographically in between two given Strings
Given two string S1 and S2 of length L, the task is to count the number of strings of length L, that exists in between S1 and S2, which are lexicographically greater than S1 but smaller than S2. Examples: Input: S1 = "b", S2 = "f" Output: 3 Explanation: These are 3 strings which come lexicographically in between S1 and S2 i.e. "c", "d" & "e"Inp
8 min read
Check whether two strings can be made equal by reversing substring of equal length from both strings
Give two strings S1 and S2, the task is to check whether string S1 can be made equal to string S2 by reversing substring from both strings of equal length. Note: A substring can be reversed any number of times. Example: Input: S1 = "abbca", S2 = "acabb" Output: Yes Explanation: The string S1 and S2 can be made equal by: Reverse S1 in the range [2,
12 min read
Print all Strings from array A[] having all strings from array B[] as subsequence
Given two arrays A[] and B[] consisting of strings, the task is to print the strings from array A[] having all strings in B[] as a subsequence.Examples: Input: A[] = {"geeksforgeeks", "mapple", "twitter", "table", "Linkedin"}, B[] = {"e", "l"} Output: mapple table linkedin Explanation: Both the strings "e" and "l" are subsets in "mapple", "table",
11 min read
Search strings with the help of given pattern in an Array of strings
Prerequisite: Trie | (Insert and Search) Given an array of strings words[] and a partial string str, the task is to find the strings of the given form str from the given array of string. A partial string is a string with some missing characters. For Example: "..ta", is a string of length 4 ending with "ta" and having two missing character at index
12 min read
Print all strings of maximum length from an array of strings
Given an array of strings arr[], the task is to print all the strings of maximum length from the given array. Example: Input: arr[] = {“aba”, “aa”, “ad”, “vcd”, “aba”}Output: aba vcd abaExplanation:Maximum length among all the strings from the given array is 3.The strings having length equal to 3 from the array are “aba”, “vcd”, “aba”. Input: arr[]
7 min read
Append digits to the end of duplicate strings to make all strings in an array unique
Given an array arr[] consisting of N strings, the task is to modify the array by replacing the duplicate strings by appending any number such that all the strings in the array are unique. Examples: Input: S = {"aa", "bb", "cc", "bb", "aa", "aa", "aa"}Output: {"aa", "bb", "cc", "bb1", "aa1", "aa2", "aa3"}Explanation:The output of the second occurren
5 min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array
Given an array arr[] consisting of N strings, the task is to find the pair of strings that is not present in the array formed by any pairs (arr[i], arr[j]) by swapping the first characters of the strings arr[i] and arr[j]. Examples: Input: arr[] = {"good", "bad", "food"}Output: 2Explanation:The possible pairs that can be formed by swapping the firs
13 min read
Convert given Strings into T by replacing characters in between strings any number of times
Given an array, arr[] of N strings and a string T of size M, the task is to check if it is possible to make all the strings in the array arr[] same as the string T by removing any character from one string, say arr[i] and inserting it at any position to another string arr[j] any number of times. Examples: Input: arr[] = {"abc", "abb", "acc"}, T = "
9 min read
Count of isogram strings in given array of strings with length at least K
Given an array arr[] containing N strings and an integer K, the task is to find the number of strings which are isograms and at least of length K. Examples: Input: arr[] = {"abcd", "der", "erty"}, K = 4Output: 2Explanation: All given strings are isograms, but only "abcd" and "erty" are of length at least K. Hence count is 2 Input: arr[] = {"ag", "b
5 min read
Count of Isogram strings in given Array of Strings
Given an array arr[] containing N strings, the task is to find the count of strings which are isograms. A string is an isogram if no letter in that string appears more than once. Examples: Input: arr[] = {"abcd", "derg", "erty"}Output: 3Explanation: All given strings are isograms. In all the strings no character is present more than once. Hence cou
5 min read
Find all Palindrome Strings in given Array of strings
Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array. Examples: Input: arr[] = {"abc", "car", "ada", "racecar", "cool"}Output: "ada", "racecar"Explanation: These two are the only palindro
6 min read
Find count of Alphabetic and Alphanumeric strings from given Array of Strings
Given an array of strings arr[] of size N. Each of the strings contains lowercase English letters or numbers only. The task is to find the frequency of alphabetic and alphanumeric strings in the array. Note: If any string has atleast one number in it, the string is an alphanumeric string. Examples: Input: arr[] = {"abcd", "mak87s", "abcd", "kakjdj"
7 min read
Make all Strings palindrome by swapping characters from adjacent Strings
Given an array of strings S[] of size X where each string has length N. In one move, you can swap the ith character of two adjacent strings, the task is to find the minimum number of moves to make every string a palindrome. If this is not possible, print -1. Examples: Input: S[] = {"13", "21", "32"}Output: 2?Explanation: We make all the strings pal
10 min read
Check if two strings can be made equal by reversing a substring of one of the strings
Given two strings X and Y of length N, the task is to check if both the strings can be made equal by reversing any substring of X exactly once. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: X = "adcbef", Y = "abcdef"Output: YesExplanation: Strings can be made equal by reversing the substring "dcb" of string X. Input:
12 min read
Count of strings in Array A that can be made equal to strings in Array B by appending characters
Given two arrays of strings SearchWord[] and FindWord[]. The task is to check how many strings in FindWord[] can be formed after the following operations on as many strings as possible: Pick a string from SearchWord[].Add one English alphabet (that is not present in that string).Rearrange the string as you like.Note: Every alphabet in the SearchWor
13 min read
Article Tags :
Practice Tags :