Home » Java programming language

Why string is immutable or final in java?



In this article, we are going to learn about Mutable and Immutable feature in java, and learn why string is immutable in java?
Submitted by Preeti Jain, on February 15, 2018

First we will understand mutability and immutability concepts.

1) Mutable

When we create an object. If we are able to change in the existing object, this behavior is nothing but mutability nature of StringBuffer.

StringBuffer class is immutable in nature.

Example:

class mutable{
	public static void main(String[] args){
		StringBuffer sb = new StringBuffer("Preeti");
		sb.append("Jain");
		System.out.println(sb);
	}
}

Output

D:\Java Articles>java mutable
PreetiJain

In the above example, only one object is created and whenever we are performing any changes in an existing object then changes will get reflect. It means we will get result like PreetiJain.

2) Immutable

When we create an object. If we are not able to change in the existing object, this behavior is nothing but immutability nature of String.

String class is immutable in nature.

Example:

class immutable{
	public static void main(String[] args){
		String s = new String("Preeti");
		s.concat("Jain");
		System.out.println(s);
	}
}

Output

D:\Java Articles>java immutable
Preeti

In the above example, only one object is created and that is pointed to an original string and whenever we are performing any changes in an existing object then changes will not get reflect. It means we will get result like Preeti.

Why String is immutable?

In the case of String, several references can point to the same object. If any changes performed by anyone reference then other references will be impacted. Thus, String is immutable in nature.

To Store string object as key in hash table whenever we are trying to access key value by key that's why string is immutable in nature. Whenever change in existing object then create an object instead changing in the existing object.

Example:

import java.util.*;

class Immutability{
	public static void main(String[] args){
		Hashtable ht = new Hashtable();
		ht.put("preeti",10);
		ht.put("Rahul",20);
		ht.put("Rajeev",30);
		ht.put("Avinash",40);

		int getValue = (int)ht.get("preeti");
		System.out.println("value of 1st key value :"+getValue);
	}
}

Output

D:\Java Articles>java Immutability
value of 1st key value :10





Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.