The main difference between mutable and immutable in Java is that mutable refers to the ability to modify a string while immutable refers to the impossibility of modifying a string.
Java is a high-level programming language that helps to develop desktop, web and mobile applications. On the other hand, a string is a set of characters. In Java, String objects are immutable. In other words, strings are unchangeable. Therefore, once the programmer creates a string object, the data and state cannot be changed. However, it is possible to create a new string object. Overall, mutable refers to the ability to modify, while immutable describes that it is not possible to modify or change.
Key Areas Covered
Java, Immutable, Mutable, String
What is Mutable in Java
Mutable refers to the ability to change or modify the string. Even though it is not possible to modify a string, there are some ways to change the string. The common way of archiving this task is by using StringBuffer and StringBuilder.
In the above program, sb1 is an object of StringBuffer. Line 6 displays the object and line 7, appends another string to sb1. Line 8 displays the object. We can see that the initial String is modified. Therefore, StringBuffer helps to change the string. Thus, it is mutable. Similarly, the StringBuilder also modifies the given string.
StringBuffer is thread-safe so multiple threads cannot access the String at the same time. On the other hand, the StringBuilder is not thread-safe. Therefore, multiple threads can access the String at the same time. Due to this reason, StringBuilder is faster than StringBuffer.
What is Immutable in Java
Immutable refers to the inability to modify the String. When the programmer creates a String, it is not possible to change it. Refer to the below example.
According to the above program, s is a reference variable. It refers to the string “Hello” in the string constant pool. Then “Hello” is combined with “World”. In this case, the initial “Hello” does not change. Instead, a new String called “Hello World” is created. Therefore, line 7 only prints “Hello”. It shows that it is not possible to change a String. In other words, a string is immutable.
Difference Between Mutable and Immutable in Java
Mutable refers to the ability to change a string while immutable refers to the impossibility of changing a string.
StringBuffer and StringBuilder are mutable while String is immutable.
String refers to a set of characters. In Java, String is immutable. On the other hand, it is possible to make a string mutable using StringBuffer or StringBuilder. The main difference between mutable and immutable in Java is that mutable refers to the ability to modify a string while immutable refers to the impossibility of modifying a string.
1.“Immutable String in Java – Javatpoint.” Www.javatpoint.com, Available here.