Detailed parameter passing in java: call by value (pass by value) and call by reference (pass by reference)


Some knowledge of parameter passing is not comprehensive.



call by value: pass by value
call by reference: pass by reference

Features:
call by value. The value is not changed, that is, the operation is a copy of the value, so the original value is unchanged.
call by reference changes the value, but does not change the reference address of the actual parameter. It can be understood that another reference also points to the same object.

Code:
public  static void  st(String str){
   // System.out.println(str.hashCode());
    str = str.replace("1","2");
   // System.out.println(str.hashCode());
}
public static void st1(StringBuffer stringBuffer){
    stringBuffer.append("S");
    stringBuffer = new StringBuffer("567");
    stringBuffer.append("890");
}
public static void main(String...args){
    String s = "123";
    st(s);
    System.out.println(s);
    System.out.println(s.hashCode(););
    StringBuffer str1 = new StringBuffer("sss");
    System.out.println(str1);
    st1(str1);
    System.out.println(str1);
}


Output result:
48690
49651
123
48690
sss
sssS
The replacement of the String class returns a new String object, and then the str reference points to the new object. In the st1 method, StringBuffer append (); the method operates on the value of the original object, and returns the original object.
stringBuffer = new StringBuffer ( "567" ); and this sentence will refer to stringBuffer pointing to the new object.

Published 26 original articles · praised 0 · visits 9936

Guess you like

Origin blog.csdn.net/weixin_38246518/article/details/78714390