In Java, an immutable class is one whose instances cannot be modified once they are created. This means that any modification to an existing instance will not change the information in that instance, but will instead create a new instance. By answering the question provided, we can confirm that java.lang.String
is an immutable class in Java.
The java.lang.String
class represents character strings. Once a String
object is created, you cannot change its content. This is what makes it immutable.
For example, if you have a String instance str = "Hello"
, and you do a str.concat(" World")
, the content of str
will not change to Hello World
. Instead, a new String instance containing Hello World
will be returned while str
maintains its original value, Hello
.
String str = "Hello";
str.concat(" World"); // str remains "Hello"
String newStr = str.concat(" World"); // newStr is "Hello World"
This immutability is designed to help String
objects become more secure, thread-safe, and usable in different areas of programming without the fear of its value being changed.
In contrast to java.lang.String, classes like java.lang.StringBuilder
, java.lang.StringBuffer
, and java.util.ArrayList
are mutable, meaning that you can change their states after they are created.
StringBuilder and StringBuffer: These classes are primarily used for creating mutable (modifiable) string objects. Any modifications made are performed on the object itself and don't require a new object creation, saving memory.
ArrayList: This class, part of Java's collection framework, represents a resizable-array implementation of the list interface. Items can be dynamically added, removed, or updated.
While mutable classes have their uses, immutability, as seen in the Java String class, presents several advantages:
Therefore, when designing your classes, consider making them immutable if it aligns with your purpose, keeping in mind these benefits.