Examples of value passing and reference passing in Java

  • 2020-04-01 02:19:55
  • OfStack


package Object.reference; 
public class People { 
    private String name; 
    private int age; 
    public People(){ 
    } 
    public People(String name, int age) { 
        super(); 
        this.name = name; 
        this.age = age; 
    } 
    public String toString(){ 
        return "name:" + name + " age:" + age; 
    } 
    public String getName() { 
        return name; 
    } 
    public int getAge() { 
        return age; 
    } 
    public void setName(String name) { 
        this.name = name; 
    } 
    public void setAge(int age) { 
        this.age = age; 
    } 
} 


package Object.reference; 
/*  java  Value passing and reference passing in  
    //www.jb51.net/clara/archive/2011/09/17/2179493.html 
    java  No reference is passed in, all values are passed  
*/
public class Test { 
    public static void swap(People a, People b, boolean flag) { 
        if (flag) { 
            //You can change the value of an object by passing a copy
            a.setName("changeName"); 
            a.setAge(100); 
        } else { 
            //Copy exchange, does not affect the main program pointer
            People c = a; 
            a = b; 
            b = c; 
        } 
    } 
    public static void main(String[] args) { 
        People p1 = new People("yingjie", 23); 
        People p2 = new People("yuexin", 20); 
        swap(p1, p2,false);//We're passing a copy of p1,p2, p1,p2, before and after the call
        swap(p1, p2,true);//What is passed is p1, a copy of p2. You can change the value of the object by passing the copy, and the contents of the p1 object change before and after the function call
    } 
} 

Related articles: