Search code examples
javaparameter-passingpass-by-referencewrapperpass-by-value

Can two numbers be swapped using wrapper class in java without creating any other class?


Here is my code to swap two numbers using wrapper class, i am aware of the fact that java only has pass by value ,so we cannot use use something like a pointer to pass the address of variables.For this i created objects for wrapper class Integer a,b.
But this code doesn't work , the comments in the code section explain my approach , Can someone please tell me where did i go wrong.

class swp{

public static void main(String[] args) {
Integer x = new Integer(5);  //x --> obj with 5 int value
Integer y = new Integer (6); //y --> obj with 6 int value


System.out.println("x = "+ x+ "   " +"y = " + y);
swap(x,y);
System.out.println("x = " + x+ "   " +"y = " + y);
}


//the values in x and y are copied in a and b 



static  void swap(Integer a,Integer b){         //a ,x--> obj with 5 int value .b,y --> obj with 6 int value
        int temp = a.intValue();              // temp contains 5
        a = b.intValue() ;                   // value at the obj ref. by a has changed to 6
        b = temp;                          //value at the obj ref. by a has changed to 5


        System.out.println("in func :  "+"a = " + a+ "   " +"b = " + b);       
}

}

output

 a = 5   b = 6
 in func :  a = 6   b = 5
 a = 5   b = 6

I know i could do this using the following approach

void swap(class_name obj1,class_name obj2){
       int temp = obj1.x;
       obj1.x =obj2.x;
       obj2.x = temp;
}

But i want to know what exactly is wrong with my approach.


Solution

  • Not using Integer directly, but you can using an Integer (or int) array. Like,

    public static void main(String[] args) {
        int[] arr = { 5, 6 };
        System.out.println("a = " + arr[0] + "   " + "b = " + arr[1]);
        swap(arr);
        System.out.println("a = " + arr[0] + "   " + "b = " + arr[1]);
    }
    
    private static void swap(int[] arr) {
        int t = arr[0];
        arr[0] = arr[1];
        arr[1] = t;
    }
    

    Which does output

    a = 5   b = 6
    a = 6   b = 5
    

    Or create a POJO like,

    class MyPair {
        private int a;
        private int b;
    
        public MyPair(int a, int b) {
            this.a = a;
            this.b = b;
        }
    
        public String toString() {
            return String.format("a = %d, b = %d", a, b);
        }
    
        public void swap() {
            int t = a;
            a = b;
            b = t;
        }
    }
    

    Then you can do

    public static void main(String[] args) {
        MyPair p = new MyPair(5, 6);
        System.out.println(p);
        p.swap();
        System.out.println(p);
    }
    

    For the same result.