Java之String,StringBuilder和StringBuffer

The char[] of StringBuilder and StringBuffer is mutable, and the char[] of String is immutable and final. StringBuilder is efficient, but thread-insecure; StringBuffer is thread-safe, but inefficient. Why String is designed to be immutable because of thread safety and String implements pass by value, not pass by reference.
The transfer between Java methods is actually the transfer of reference copies: the code is as follows:
public String change(String s, int i, StringBuffer sb, Person p){
	        s="123"; //Change the pass-by-reference copy
	        i=3;
	        sb.append("woshi"); //Change the content of the passed value
	        p.setAge(100);//Change the content of the passed value
	        sb = new StringBuffer("sbsb"); //Change pass-by-reference copy
	        p = new Person("bb",44); //change the pass-by-reference copy
	        return s;
	    }
	 
	    public void testChange(){
	        StringBuffer sb = new StringBuffer("buff");
	        String s = "aaa";
	        int i = 1;
	        Person p = new Person("aa",12);
	        i=2;
	        change(s,i,sb,p);
//	        s="222";
	        System.out.println(s);
	        System.out.println(i);
	        System.out.println(sb.toString());
	        System.out.println(p);
	    }


output:
aaa
2
buffwoshi
Person [name=aa, age=100]
 From a virtual machine perspective:
This problem can be well understood from the perspective of the Java virtual machine. It is very simple. First, local variables and method parameters will be stored in the stack space, and the new ones will be stored in the heap space. When the program executes stringbuffer sb=new stringbuffer(), first allocates a variable sb (a reference address) in the stack space, and then allocates a real object in the heap space, sb points to this object, when the change(stringbuffer sb) method is called, the stack space will be Copy a reference of sb, which also points to the object of heap space sb (at this time, there are two sb reference variables in the stack space, and they point to the same object at the same time). After executing sb.append("aa"), the content of the sb object will be changed. No problem, when sb=new stringbuffer(); is executed, the sb reference of the copy will re-point to a new new object. After the method is executed, the sb reference variable of the stack space copy disappears (if there are no other references pointing to it, it It will wait for the garbage collector to recycle), after returning to the main method, the sb reference declared for the first time still points to the original sb object.
Partially taken from: https://www.cnblogs.com/woshimrf/p/5263018.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326454624&siteId=291194637