×

Why String in Immutable in Java?

Why String in Immutable in Java

Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change in the string leads to the creation of the new string, and the current string remains untouched. Let’s understand the immutability of Java strings with the help of the following example.

FileName: StringImmutableExample.java

 public class StringImmutableExample
{ 
// main method
public static void main(String argvs[])
{
// Input string
String str1 = "Tutorial & Example";
// Doing the concatenation work
str1.concat(" – A Good Site To Learn Java.");
System.out.println(str1);
}
} 

Output:

Tutorial & Example


Explanation: The output shows that even the concatenation on the string str does not change the content of the string. When the concat() method is invoked on the string str, a new string is created. However, the new string is automatically destroyed as no reference is holding that new string. If the reference variable str gets updated and holds the reference of the new string, the old string gets destroyed. Let’s confirm it with the help of an example.

FileName: StringImmutableExample1.java

 public class StringImmutableExample1
{ 
// main method
public static void main(String argvs[])
{
// Input string
String str1 = "Tutorial & Example";
// Updating the reference variable str1
str1 = " – A Good Site To Learn Java. ";
System.out.println(str1);
}
} 

Output:

– A Good Site To Learn Java.

Explanation: The output shows the updated string. Behind the scene, the object of the “Tutorial & Example” string gets destroyed, as we have updated the reference of the variable str1. Note that at no point of time the string “Tutorial & Example” gets manipulated.

FileName: StringImmutableExample2.java

 public class StringImmutableExample2
{ 
// main method
public static void main(String argvs[])
{
// Input string
String str1 = "Tutorial & Example";
// Doing the concatenation work
str1 = str1.concat(" – A Good Site To Learn Java.");
System.out.println(str1);
}
} 

Output:

Tutorial & Example – A Good Site To Learn Java.

Explanation: In the above code, the reference variable str is holding the reference of the concatenated string. Hence, this time the old string gets reference less and hence, destroyed.

Reason Behind Immutability

The reason behind immutability is the usage of a string literal in Java. When a string literal is assigned to a variable, the variable holds the reference of the string literal as the string literal is treated as an object in Java. One can also create another variable that holds the reference of the same string literal.

Thus, we have two reference variables holding the reference of the same string literal. Hence, if one changes the value of the string literal using one reference variable, the changes get reflected for the other reference variable too, which is bad, as the second reference variable did nothing to change the value of the string literal. Therefore, to avoid the same strings made immutable in Java.


Related Topics

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.