Why is a Java string an immutable object? (1)
This article mainly introduces immutable objects in Java and immutable String classes in Java. Why is the Java String class immutable? Let's take a look.
Answer 1:
One of the most popular Java interview questions is: what are immutable objects, what are the benefits of immutable objects, when should they be used, or, more specifically, why is the Java String class set to the immutable type?
Immutable object, as its name implies, is an object that cannot be changed after creation. A typical example is the String class in Java.
- String s = "ABC";
- s.toLowerCase();
The above s. toLowerCase () does not change the value of "ABC", but creates a new String class "abc" and points the new instance to the variable "s.
Compared with mutable objects, immutable objects have many advantages:
1). Immutable objects can improve the efficiency and security of the String Pool. If you know that an object is immutable, when you need to copy the content of this object, you do not need to copy its own instead of just copying its address, the replication address (usually the size of a pointer) requires a very small memory efficiency. Other variables that reference this "ABC" at the same time will not be affected.
2 ). immutable objects are safe for multithreading, because when multithreading is performed simultaneously, the value of a mutable object may be changed by other processes, which may lead to unexpected results, this situation can be avoided by using immutable objects.
Of course there are other reasons, but the biggest reason for Java to set String to immutable is efficiency and security.