Home Java javaTutorial Is the String object in java mutable?

Is the String object in java mutable?

Dec 05, 2016 am 10:54 AM
java

A friend posted a question on StackOverflow and asked:

It is known that the String object in Java is immutable, but let’s take a look at the following code:

String s1 = "Hello World";  
String s2 = "Hello World";  
String s3 = s1.substring(6);  
System.out.println(s1); // Hello World  
System.out.println(s2); // Hello World  
System.out.println(s3); // World  

Field field = String.class.getDeclaredField("value");  
field.setAccessible(true);  
char[] value = (char[])field.get(s1);  
value[6] = 'J';  
value[7] = 'a';  
value[8] = 'v';  
value[9] = 'a';  
value[10] = '!';  

System.out.println(s1); // Hello Java!  
System.out.println(s2); // Hello Java!  
System.out.println(s3); // World
Copy after login

Why is this code like this? operation result? Why are the values ​​of s1 and s2 changed, but the value of s3 is not?

Answer #1:

String objects are immutable, but that just means that you cannot change its value by calling its public methods.

The above code bypasses the normal API through reflection mechanism. In this way, you can also change the value of the enumeration, and even change the lookup table used when the Integer type is autoboxed.

Here, since s1 and s2 point to the same internal string object, their values ​​are both changed. As mentioned in other answers, this is implemented by the compiler.

The reason why s3 has not been changed really surprises me. I used to think that s3 and s1 share the same value array (this was indeed the case in versions before Java 7u6). However, by looking at the source code of the String class, we can see that the value array of the substring object is copied from the original string object (by using the Arrays.copyOfRange(..) method). This is the reason why s3 has not been changed.

You can install a SecurityManager to prevent malicious code from performing this type of operation. But it should be noted that the implementation of some libraries relies on this reflection technique (such as ORM tools, AOP libraries, etc.).

I wrote at the beginning of my reply that String objects are not really immutable, they just "look immutable". This may mislead readers into thinking that the current version of the String class is negligent in terms of access restrictions, but in fact the value array uses private and final modifiers. Therefore, developers need to pay attention: arrays cannot be declared immutable in Java, and even if the correct access modifiers are used, they cannot be exposed outside the class.

Since this topic is so hot, I recommend some advanced reading to you: Heinz Kabutz’s crazy speech about reflection technology at the 2009 JavaZone conference. This article covers common problems in reflection operations, as well as other content about reflection technology. . This article is very good and very crazy.

This article reveals why reflection techniques are useful in certain scenarios, but in most cases you should avoid using it.

Answer #2:

In Java, if two variables of type String are initialized to the same string, then both variables will be assigned the same object reference. This is why the expression "Test1==Test2" returns true.

String Test1="Hello World";
String Test2="Hello World";
System.out.println(test1==test2); // true
Copy after login

Is the String object in java mutable?

Test3 is a new String object created by the substring() method. It does not share the same value array with Test1. (Note: Due to a clerical error by the original author, the first letters of the variables test1 and test3 in the picture below are not capitalized. Please pay attention to the readers)
We can access the String object through reflection technology and obtain the pointer of the value array:

Is the String object in java mutable?

Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
Copy after login

Change The value of this value array can change the value of all String objects holding the array pointer, so the values ​​of Test1 and Test2 have changed. But since Test3 is a new String object created by the substring() method, its value has not been changed.

Is the String object in java mutable?


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles