×

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

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.