Does string really have to be immutable?

Source: Internet
Author: User

You may ask a person if the string is variable? Presumably they would all say the same. The string is immutable, because the string is final decorated, and it is the final modified char[] array at the bottom.

You can see the string source code:

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

So the string is not to become, but we ignore the reflection, using reflection we can change the value of the string, say not much about how reflection is done:

public static void main(String[] args) throws Exception {        // 创建字符串"Hello World", 并赋给引用s        String s = "Hello World";        //把这个s保存一份用于对比        String temp = s;        System.out.println("s和temp是否相等? " + s.equals(temp));        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        System.out.println("s和temp是否相等? " + s.equals(temp));    }

We can see that we have used reflection to bypass the private permissions and modified the char[] array at the bottom of the string, and I want to read the little partner of this article. Do you know what to say when someone asks if the string is mutable?

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.