Why String Class is Immutable or Final in Java



The general meaning of immutable is something that cannot be changed or modified after creation. In Java, a string is immutable; we cannot change the object itself, but we can change the reference to the object. The string is made final to not allow others to extend and modify it. When you modify a string, a new copy of the string with your modifications is created.

This article will explain what a String is and why it is immutable and final in Java.

What is a String?

Like other object-oriented programming languages, almost every component of Java is an object, including strings. The string that stores an array of characters is an object of the String class. The String class belongs to java.lang package.

Example

In the Java program given below, we are creating a String from a character array:

public class ExampleStrings {
   public static void main(String[] args) {
      char charsArr[] = { 'T', 'U', 'T', 'O', 'R', 'I', 'X' }; 
	  // creating string from character array
      String str = new String(charsArr); 
      System.out.println("The given string: " + str);
   }
}

The above code will print the string:

The given string: TUTORIX

Why String is Immutable and Final?

The string in Java is immutable and final for the following reasons:

  • Security Parameters are represented as a String in network connections, database connection URLs, usernames, and passwords, etc. If it is mutable, these parameters could be changed easily.

  • To solve synchronization and concurrency issues in multithreading, Strings are immutable.

  • When the compiler optimizes String objects, two string objects with the same value (a =" test", and b =" test") require only one string object (for both a and b, these two will point to the same object).

  • String is used as an argument for class loading. If it is mutable, the string value could result in the wrong class being loaded because mutable objects change their state.

Example: Demonstrating String Immutability

A Java program that shows a string in Java is immutable is as follows:

public class StringImmutableDemo {
   public static void main(String[] args) {
      String st1 = "Tutorials";
      String st2 = "Point";
      System.out.println("The hascode  of st1 = " + st1.hashCode());
      System.out.println("The hascode of st2 = " + st2.hashCode());
	  // concatenation
      st1 = st1 + st2;
      System.out.println("The Hashcode after st1 is changed : "+ st1.hashCode());
   }
}

Output

On running, the above code will concatenate two strings and display the hash code. You will get two different hascodes for the same string before and after modification, which shows the string is immutable.

The hascode of st1 = -594386763
The hascode of st2 = 77292912
The Hashcode after st1 is changed : 962735579
Updated on: 2025-05-16T15:48:37+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements