0

In Java, it seems that the primitive data type arguments will pass into the method by value. But what if I want to swap the values of two integers.

public static void main(String[] args){
   int a = 1;
   int b = 2;
   swapvalue(a,b);
   System.out.println(a);
   System.out.println(b);    
}

public static void swapValue(int a, int b){
   int c = a;
   a = b;
   b = c;
}

For example, the code above is aimed to swap the values of a and b. In C++ I can pass into the pointers or references to them but I have no idea about how to do this in Java without pointers. How could I make it?

Kidsunbo
  • 1,024
  • 1
  • 11
  • 21

1 Answers1

2

You can't swap them by passing them to a method.

The closest thing you can do is pass an int[] to the method, and swap the elements of the array :

public static void main(String[] args){
   int[] arr = {1,2};
   swapValues(arr);
   System.out.println(arr[0]);
   System.out.println(arr[1]);    
}

public static void swapValues(int[] arr){
   int c = arr[0];
   arr[0] = arr[1];
   arr[1] = c;
}

Another alternative is to wrap them with some mutable class :

public class IntHolder
{
    private int value;
    ...
}

public static void main(String[] args){
   IntHolder a = new IntHolder(1);
   IntHolder b = new IntHolder(2);
   swapValue(a,b);
   System.out.println(a.getInt());
   System.out.println(b.getInt());    
}

public static void swapValue(IntHolder a, IntHolder b){
   int c = a.getInt();
   a.setInt(b.getInt());
   b.setInt(c);
}
Eran
  • 387,369
  • 54
  • 702
  • 768