Home > Back-end > The String class based applications, consult with code
The String class based applications, consult with code
Time:11-21
Small program: exchange method swap string a and b, pointing to the sample, why not exchange a success?
public static void swap1 (String a and String b) {//exchange a and b String temp=b; B=a; A=temp. System. The out. Println (a + "" + b);//output A, B } Public static void swap2 (String [] s) { String \ [0]=s; S [0]=s [1]; S [1]=temp; } Public static void main (String [] args) {
String a="a". String b="b"; String [] s={" 1 ", "2"}; Swap1 (a, b); Swap2 (s); System. The out. Println (a + "" + b);//here why output A B? The String class is final types of reference data types, method isn't swap1 transfer reference? Why not output A B? System. The out. Println (s [0] + "" + s [1]).//output 2 1, here I can understand }
CodePudding user response:
Array variable s reference {" 1 ", "2"} array object, methods swap2 is the reference, the book says the String and reference data types, variables, a reference to "a" String objects, variable reference b "b" String objects, swap1 also is the reference, but the output is not the case, is not the whole of me? .
CodePudding user response:
In reference type as a parameter, the pass is a copy of address values, but the two address point to the same place, no changes in copy address point, to perform operations on data copy address to affect the value of the original data String is special, his is final, it is the underlying a final type of ch [] array, it is immutable, every time you make changes to it is led it to a new object, it is the value of the original address change
CodePudding user response:
This article https://www.cnblogs.com/jagh/p/jjjj.html for reference
CodePudding user response:
Like nine swords dugu finale: Java pass parameters, the method is to copy a variable, and then the incoming method body to carry out,
Under the simple analysis: 1, the String a="a"; --> In the JVM heap heap1 opened up A piece of memory, memory value "A", in the stack is allocated to A A memory walks, walks in storing the addresses of heap1 2, the swap1 (a, b); --> JVM is a copy of a, called a2, and assigned a memory stack2, deposit is also the address of the heap1, a2 into the method swap1 3, is actually in the way of a2, so the method is out of print a2 4, after the method, method to print a, since the store is heap1 address, or a
String b="b"; Similarly
CodePudding user response:
String is special, can't exchange, consider using StringBuffer as a parameter,
CodePudding user response:
Change your code, you can generate the results you want Public static void swap1 (String a, String b) {//exchange a and b String temp=b.i ntern (); B=Anderson ntern (); A=temp. System. The out. Println (a + "" + b);//output A, B }