search
HomeJavajavaTutorialWhy is the String class in Java immutable (detailed explanation)

Why is the String class in Java immutable (detailed explanation)

Why the String class in Java is immutable (detailed explanation)

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];}

The value of the String class is stored in in the value array, and is modified by private final

1. Private modification indicates that external classes cannot access value, and subclasses cannot access it. Of course, the String class cannot have subclasses. , because the class is final modified
2, final modification, indicating that the reference of value will not be changed, and value will only be initialized in the constructor of String, and there is no other way to modify the value in the array Value ensures that the reference and value of value will not change

So we say that the String class is immutable.

And many methods, such as substring, do not operate on the original String class, but generate a new String class

public String substring(int beginIndex) {
	if (beginIndex < 0) {
		throw new StringIndexOutOfBoundsException(beginIndex);
	}
	int subLen = value.length - beginIndex;
	if (subLen < 0) {
		throw new StringIndexOutOfBoundsException(subLen);
	}
	return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);}

Why is String set to be disabled? changing?

String constant pool

Java has 8 basic data types

Integer types: byte, short, int, long. Packaging types are Byte, Short, Integer, Long
Floating point types: float, double. The packaging type is Float, Double
Character type: char. The packaging type is Character
Boolean type: boolean. The packaging type is Boolean

Except Float and Double among the 8 packaging types, the constant pool is not implemented. The rest are implemented. Of course, they are all constants of the String class implemented through the flyweight mode. Pools are implemented at the JVM level.

Why is there a constant pool? The constant pool is used to avoid frequent creation and destruction of objects that affects system performance, and it implements object sharing.

For example, the string constant pool puts all string literals into a constant pool during the compilation phase.

    Save memory space: All identical string constants in the constant pool are merged and only occupy one space.
  • Save running time: When comparing strings, == is faster than equals(). For two reference variables, just use == to determine whether the references are equal, and you can also determine whether the actual values ​​are equal.
Where is the string constant pool?

I will not discuss anything before jdk1.7. Starting from jdk1.7, the string constant pool began to be placed in the heap, and then all the contents of this article are based on jdk1.8

The following code is often asked

String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
String str4 = new String("abc");
// trueSystem.out.println(str1 == str2);
// falseSystem.out.println(str1 == str3);
// falseSystem.out.println(str3 == str4);

The structure in memory is as follows


Why is the String class in Java immutable (detailed explanation)The constant pool stores references
Explain the output of the above code. There are two ways to create string objects in Java

String str1 = "abc";
String str2 = "abc";
// trueSystem.out.println(str1 == str2);

When creating a string using a literal value, the JVM will first remove the string Find whether the object "abc" exists in the pool

If it does not exist, create the object "abc" in the string pool, and then assign the address of the object "abc" in the pool to str1, so that str1 It will point to the string object "abc" in the pool

If it exists, no object will be created, and the address of the "abc" object in the pool will be directly returned and assigned to str2. Because str1 and str2 point to the "abc" object in the same string pool, the result is true.

String str3 = new String("abc");
String str4 = new String("abc");
// falseSystem.out.println(str3 == str4);

When using the new keyword to create a string object, the JVM first searches for the string object "abc" in the string pool.

If not, it first searches the string object in the string pool. Create an "abc" string object in the pool, then create an "abc" string object in the heap, and then assign the address of the "abc" string object in the heap to str3

If there is one, Then instead of creating the "abc" object in the pool, create an "abc" string object directly in the heap, and then assign the address of the "abc" object in the heap to str4. In this way, str4 points to the "abc" string object created in the heap;

Because str3 and str4 point to different string objects, the result is false.

Cache HashCodeWhen the String class is created, the hashcode is cached in the hash member variable because the String class is immutable , so the hashcode will not change. In this way, every time you want to use the hashcode, you can just get it directly without recalculating it, which improves the efficiency.

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {

    /** Cache the hash code for the string */
    private int hash; // Default to 0
	}

Can be used as the key of HashMapDue to the immutable nature of the String class, it is often used as the key of HashMap. If the String class is variable and the content changes, the hashCode will also change. When fetching it from the HashMap based on this key, it may not be fetched. value, or get the wrong value

Thread safetyImmutable objects are inherently thread-safe, which can avoid problems in a multi-threaded environment Next, perform synchronization operations on String.

Thank you everyone for reading, I hope you will benefit a lot.

This article is reproduced from: https://blog.csdn.net/zzti_erlie/article/details/106872673

Recommended tutorial: "java tutorial"

The above is the detailed content of Why is the String class in Java immutable (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft