Run the following code, what is the 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 = "test ok"; ch[0] = 'g'; } }
The results are as follows:
good gbc
Commentary:
String in Java is immutable, that is, immutable. Once initialized, the content pointed to by its reference is immutable (note: the content is immutable).
In other words, assuming that there is String str = "aa"; str = "bb"; in the code, the second statement does not change the content of the original storage address of "aa", but opens up another space. Used to store "bb"; at the same time, because "aa" that str originally pointed to is now unreachable, jvm will automatically recycle it through GC.
When calling a method, the String type and array are passed by reference. 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 pointed to by str in the class, but str = "test ok"; statement makes the method parameter str point to the newly allocated address, which stores "test ok", while the original str still points to "good". For arrays, in the change method, the method parameter ch points to the array pointed to by ch in the class, and the ch[0] = 'g'; statement changes the contents of the array pointed to by ch in the class
Let’s take a look at the following code again. What is the result of its operation?
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 results are as follows:
good abc
With the previous explanation, is this result expected? !
The above introduction to the assignment of String type variables in Java is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.