Why is a Java string an immutable object? (1)

Source: Internet
Author: User

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.

 
 
  1. String s = "ABC"; 
  2. 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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.