The value assignment of String type variables in java.
What is the result of running the following code?
package com.test;public class Example { String str = new String("good"); char[] ch = { 'a', 'b', 'c' }; public static void main(String[] args) { Example ex = new Example(); ex.change(ex.str, ex.ch); System.out.println(ex.str); System.out.println(ex.ch); } public void change(String str, char ch[]) { str = "test ok"; ch[0] = 'g'; } }
The result is as follows:
goodgbc
Explanation:
In java, String is immutable, that is, immutable. Once initialized, the referenced content is immutable (Note: The content is immutable ).
That is to say, if the Code contains String str = "aa"; str = "bb"; then the second statement does not change the content in the original storage address of "aa, instead, it opened up another space to store "bb". At the same time, because the "aa" originally pointed to by str is no longer reachable, jvm will automatically recycle it through GC. During method calling, the String type and array are referenced and passed. In the above Code, str is passed as a parameter to the change (String str, char ch []) method, the method parameter str points to the string indicated by str in the class, But str = "test OK"; the statement causes the method parameter str to point to the new address, which is stored as "test OK ", the original str still points to "good ". For arrays, In the change method, the method parameter ch points to the array indicated by ch in the class, ch [0] = 'G '; the statement changes the content of the array pointed to by ch in the class.
Let's take a look at the following code. What is the running result?
package com.test;public class Example { String str = new String("good"); char[] ch = { 'a', 'b', 'c' }; public static void main(String[] args) { Example ex = new Example(); ex.change(ex.str, ex.ch); System.out.println(ex.str); System.out.println(ex.ch); } public void change(String str, char ch[]) { str = str.toUpperCase(); ch = new char[]{ 'm', 'n' }; } }
The result is as follows:
goodabc
With the previous explanation, is this result expected ?!
Here is an article worth reading:
Three-minute understanding of the storage and assignment principles of strings in Java http://blog.csdn.net/zhuiwenwen/article/details/12351565