Change the value of a string without changing the direction of memory in Java __java

Source: Internet
Author: User

Previously thought that string is final, in Java can not be modified, but today when the interview asked this question, I replied that if you really want to modify the physical address of the data, and then looked back, this can also be modified:

A string object is placed in a shared memory pool, and when you create a string, see if there is one in the pool, return it, or create it.

package com.leon.demo;      import java.lang.reflect.field;       public class stringdemo {       public static void  main (String[] args)  throws Exception {            String str01 =  "AAA";            String str02 =  "AAA";           string  str03 =  "BBBB";           system.out.println ( Str01.hashcode ()  +  "/"  + str02.hashcode ()  +  "/"  + str03.hashcode ());            field field = str02.getclass (). Getdeclaredfield ("value");           field.setaccessible (True );   &NBsp;       field.set (str02,new char[] {  ' B ',  ' B ',  ' B ',  ' B '});           system.out.println (str01 +   "/"  + str02);           field =  Str02.getclass (). Getdeclaredfield ("Count");            Field.setaccessible (True);           field.set (str02,4);               system.out.println (str01 + ) /" + str02);           system.out.println ( Str01.hashcode ()  +  "/"  + str02.hashcode ()  +  "/"  + str03.hashcode ());            field = str02.getclass (). Getdeclaredfield ("hash");    &NBsp;      field.setaccessible (true);            field.set (str02,0);            System.out.println (Str01.hashcode ()  +  "/"  + str02.hashcode ()  +  "/"  +  Str03.hashcode ());           system.out.println (str01 ==  STR02);           system.out.println (str02 ==  STR03);       }  }  operation results are as follows: 
Java code 96321/96321/3016832 bbb/bbb bbbb/bbbb 96321/96321/3016832 3016832/3016832/3016832 true false According to Java The attributes of string, Str01 and Str02 point to the same memory address, so str01,str02 always remain consistent. The nature of a string cannot be modified is a final character array (private final char value[];), but final is only valid at compile time, and the runtime is not useful, so you can modify the value of the array by reflection. The hashcode of the modified string in the code does not change because the string object caches the hashcode and can see the change without caching. Based on the attributes of the Java string, all of the string objects created by the above code are stored in string pool with the same str02 and str03 in the code, so there are two identical strings in the string pool. As for Hashcode Why didn't change we see the source is also very clear

public int hashcode () {
int h = hash;
if (h = = 0) {
int off = offset;
Char val[] = value;
int len = count;

for (int i = 0; i < len; i++) {
H = 31*h + val[off++];
}
hash = h;
}
return h;
}

Java to improve efficiency, only the first time the Hashcode function to generate a hash, and the value exists in this instance. Later, the new hash is no longer generated even if the value of the values of the value array changes.

Finally, sigh, the reflection mechanism is really powerful ah.


First, the reflection mechanism does not have access to private members. Only public members can be accessed. At least my code is not tested. Otherwise, what kind of encapsulation can say?

Second, there are many reasons why a string cannot be changed. Not only is the value final, but the class is final, and value is private, and these are only auxiliary measures to enhance the immutability of the string, and are not guaranteed to be immutable. Because the Java object variable stores the reference. Vlaue as an array is also a reference. Final can only guarantee that it always points to the same array object, but to ensure that the array itself access without changing the contents of each element, only through its external methods to ensure that only read. The char array passed by the external construction method must be copied first to prevent external modification. Of course, in order to conserve resources there is a construction method that can pass an array object directly, without copying it. But this can easily disrupt encapsulation, allowing the outside world to change string values through array objects. So this construction method is accessed within the package. And string is under the Java.lang package. The Java package is protected, the outside can not be modified, that is, the inside of the class are written by Sun, very safe.

These measures only guarantee the immutability of the string

Attach three minutes to understand the storage and assignment principle of strings (string) in Java

Many Java beginners may be puzzled by string storage and assignment, and here is a simple test case that you can only take a few minutes to understand.

1. Before you look at the examples, make sure you understand the following terms:

Stacks : The JVM allocates areas to hold actions and data references that are executed by the thread. Stack is a running unit, in Java a thread will have a corresponding line stacks.

Heap : a region that is allocated by the JVM to store data such as objects.

constant Pool : A storage area allocated in a heap that is used to store explicit string,float or integers. For example, String str= "abc"; ABC This string is explicitly declared, so it is stored in a constant pool.

2. See this example, use jdk5+junit4.5 to write example, completely through the test Java code import static org.junit.Assert.assertNotSame;      Import static org.junit.Assert.assertSame;      Import Org.junit.Test; /** * @author HEIs * */public class stringtest{@Test public void

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.