Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Why is String immutable in Java?


May 28, 2021 Article blog



Why isn't the string in Java variable? I believe everyone has this question, this article tells you the answer.

Why string is not variable

The String class uses an array of char types that are finally decorated to store characters, as follows:

/** The value is used for character storage. */
private final char value[];

Why string is not variable

The String class uses an array of char types that are finally decorated to store characters, as follows:

/** The value is used for character storage. */
private final char value[];

Is String really immutable?

1, String immutable but does not represent the reference immutable

String str = "Hello";
str = str + " World";
System.out.println("str=" + str);xi

effect:

str=Hello World

Parsing: String content is immutable because str changes from the memory address that originally pointed to "Hello" to the memory address of "Hello World", so it opens up more memory areas to the "Hello World" string.

2, through reflection can modify immutable objects

// 创建字符串"Hello World", 并赋给引用s
String s = "Hello World";

System.out.println("s = " + s); // Hello World

// 获取String类中的value字段
Field valueFieldOfString = String.class.getDeclaredField("value");

// 改变value属性的访问权限
valueFieldOfString.setAccessible(true);

// 获取s对象上的value属性的值
char[] value = (char[]) valueFieldOfString.get(s);

// 改变value所引用的数组中的第5个字符
value[5] = '_';

System.out.println("s = " + s); // Hello_World

effect:

s = Hello World
s = Hello_World

parse:

Access private members with reflection, then reflect out the value property of the object, and then change the value reference to change the array structure.


That's what the editor-in-chief brings you about why String in Java is immutable? the whole content.