Analysis of value transfer and reference transfer in java, analysis of java transfer reference
public class Test { public static void main(String[] args) { String s = new String("aaa"); change(s); System.out.println(s); StringBuilder sb = new StringBuilder("111"); change(sb); System.out.println(sb); } static void change(String s){ s = new String("bbb"); } static void change(StringBuilder sb){ sb.append("333"); }}
Print result:
Aaa
111333
========================================================== ========================================================== ==========
As shown in the code above,
String s = new String ("aaa"); it is actually String s = "aaa"; but the java background will automatically encapsulate it for us;
The change (s) Here is the value transfer. The value transfer is actually a copy of the transmitted data and will not affect the original value, in java, the eight basic data types and the String type are passed as values.
========================================================== ========================================================== ============
Next we will talk about the transfer of references.
As shown in the code above,
StringBuilder sb = new StringBuilder ("111"); sb points to new StringBuilder ("111 ")
When you change (sb), the reference of sb is passed. So when sb modifies the value, the original sb is also modified because they point to the same memory.
In java, the transmission between objects is mostly reference transmission.
========================================================== ========================================================== ===
The above is my rough insight into the value transfer and reference transfer in java. You are welcome to give guidance and criticism.