How to exchange the contents of two integers in JAVA?

In the C language, we have learned to exchange two integers with pointers, but there are no pointers in Java, so they will be exchanged by reference.

class MyValue{
    
    
    public int val;
}


public class TestDemo {
    
    
    public static void swap(MyValue a,MyValue b){
    
    
        int tmp=a.val;
        a.val=b.val;
        b.val=tmp;
    }


    public static void main(String[] args) {
    
    

        MyValue myValue1=new MyValue();
        myValue1.val=10;
        MyValue myValue2=new MyValue();
        myValue2.val=20;
        swap(myValue1,myValue2);
        System.out.println(myValue1.val+"  "+myValue2.val);
     }
  }
      

Guess you like

Origin blog.csdn.net/m0_46551861/article/details/107603602