Run the following code, what's 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:
Explanation:
In Java, a string is immutable, which is immutable, and once initialized, its reference to the content is immutable (note: content is immutable).
In other words, suppose that there is a string str = "AA" in the code; str= "BB", the second statement does not change the contents of the "AA" stored address, but it also opens up a space for storing "BB", and since the "AA" originally pointed to by STR is now unreachable, The JVM is automatically recycled via GC.
At the time of method invocation, the string type and array belong to the reference Pass, in which STR is passed as a parameter to the change (string str, char ch[]) method, and the method parameter str points to the string that str points to in the class, but str= "test OK"; The statement causes the method parameter str to point to the newly assigned 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 an array of CH in the class, ch[0] = ' g '; The statement changes the contents of the CH-oriented array in the class
Let's take a look at the following code, what is the result of the 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:
With the previous explanation, is the result not expected?!
Above this Java in the String type variable assignment problem introduction is small series share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.