Java/J2EE and SOA (239 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (46 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (239 Blogs)
  • Spring Framework (8 Blogs)


myMock Interview Service for Real Tech Jobs


What are Immutable String in Java and how to use them?

Published on Aug 29,2019 78 Views
Research Analyst at Edureka. A techno freak who likes to explore different... Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write about...
39 / 90 Blog from Java Fundamentals


myMock Interview Service for Real Tech Jobs


myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

While working in Java, you might have come across the phrase saying, “String is Immutable in Java”. But have you ever wondered why it is so? Through the medium of this Immutable String in Java article, I will be confronting this particular question and provide you with complete insights.

Below are the topics I will be discussing in this Immutable String in Java article:

Let’s get started.

Introduction to Immutable String in Java

Before I talk about Immutable String in Java, let me first enlighten you about what are immutable objects in Java. An immutable object is that object which won’t change its internal state once it is created. In case you want to change its value later in course, Instead, first, you need to clone it and then change the clone’s value while creating it.

Coming back to Java String, String refers to a sequence of characters. In Java, String is an in-built class that belongs to the lang package. As mentioned before the objects of String class are “Immutable in Nature”.  In other words, once created, the instances of this class cannot be modified by any means. 

The Java String can be created in two ways:

  1. Using String Literal

    String name = "Edureka" ;
  2. Using ‘new keyword

    String name = new String("Edureka");

When you create a Java String using String literal, it creates the String within a String pool. But when you use the ‘newkeyword to create the String, then it creates two objects; one in String pool and one in heap. If you want to learn more about these two methods, you can refer to the Java String article.

Let me now give you an example for your better understanding of Immutable String in Java.

class ImmutableDemo{  
 public static void main(String args[]){  
   String name = "Edureka";  
   name.concat(" Learning"); //concat() method appends the string at the end  
   System.out.println(name); //will print Edureka as Strings are immutable objects  

Now, let’s move ahead with this Immutable String in Java article and learn about the reasons for a String to be immutable in nature.

Why String is Immutable in Java?

In Java, there are mainly 5 main reasons which I have discussed below in detail:

  • String Pool

Java String pool refers to a collection of Strings that are stored in heap memory. In this, whenever a new object is created using a String literal, String pool first checks whether the object is already present in the pool or not. If it is, then the same reference is returned to the variable else a new object is created within the String pool and the respective reference is returned. Refer to the diagrammatic representation for better understanding:

String pool - Immutable String in Java - Edureka

  • HashCode Caching

String objects are heavily used with hash implementations such as HashMap, HashTable, HashSet, etc. While working with the hash implementations, the hashcode is used for bucketing the data. The immutability of the String ensures that the value of the hashcode remains the same after its creation. Thus even if the later the data is updated the same hashcode will be returned without having to recalculate it. This leads to better efficiency and performance of the application.

In case the Strings were mutable in nature, then when you update your data, the hashcode produced at the time of insertion and retrieval of the contents of String would be different from each other. This can lead to loss of value objects within the Map.

In the String class, the following code is used to cache the hash code.

private int hash;
  • Synchronization

Java Strings are naturally thread-safe because of their immutability. This means that they can’t be altered or modified when accessed by multiple threads at the same time. Thus, in case any thread tries to alter the original value of the object, then instead of updating the former one, a new String object will be created in the String pool. So, you can freely use Strings for multithreading concepts in Java without having to synchronize them.

  • Security

Immutable String in Java is widely used as a parameter for the Java applications. These help in storing sensitive sets of information such as username, passwords, network connections, URL and many more. Thus, if Java Strings were not immutable in nature then anyone could easily alter the connection name or passwords which would ultimately lead to serious security threats. Moreover, Strings are also used by the JVM for loading a class. The immutability of Java Strings provides security by ensuring that the correct class is getting loaded by Classloader. For instance, suppose you want to load java.sql.Connection class but the referenced value is altered to myhacked.Connection class to perform unauthorized actions on your data. Below I have demonstrated a small code for the same:

boolean connect(string url){
    if (!isSecure(url)) { 
throw new SecurityException(); 
//Following will generate issue in case url is changed
//before this by using other references.    

  • Performance

All the above four topics boast the advantages of having immutable String in Java. As you already know, String is a widely implemented concept in Java applications, on whole, it helps in enhancing the application’s performance as well as security.

This brings us to the end of this article on Immutable String in Java. If you want to know more about Java you can refer to our other Java Blogs.

Now that you have understood the concept of Immutable String in Java, check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Immutable String in Java” article and we will get back to you as soon as possible.


Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.