Value passing and reference passing for java parameter passing

  • 2021-08-17 00:10:57
  • OfStack

Value passing

When a method is called for value passing, a local variable is generated inside the method. Using the value of the local variable inside the method does not affect the value of the original data passed in, including in wrapper classes using basic data types.


public class Assc
{
 public static void main(String[] args)
 {
 int x1=1;
 add(x1);
 System.out.println(" Ultimately "+x1);//1
 Integer x2=new Integer(1);
 sub(x2);
 System.out.println(" Ultimately "+x2);//1
 }
 public static void add(int x) {
 x++;
 System.out.println(x); //2
 }
 public static void sub(Integer x) {
 x--;
 System.out.println(x);//0
 }
 
}

Reference passing

When calling a method with reference type parameters, the data with the same address as the passed-in parameter is used. Modifying the parameters inside the method will cause the original data to change (except for String type)

When String type data is passed in, the operation is to create a new string in the string constant pool without affecting the value of the original string


public class Assc
{
 public static void main(String[] args)
 {
 String str="hello";
 combine(str);
 System.out.println(" Ultimately "+str);//hello
 StringBuilder sb=new StringBuilder("nihao");
 combine2(sb);
 System.out.println(" Ultimately "+sb);//nihaoworld
 }
 
 public static void combine(String str) {
 str+="world";
 System.out.println(str);//helloworld
 }
 public static void combine2(StringBuilder str) {
 str.append("world");
 System.out.println(str);//nihaoworld
 }
}

Related articles: