1

How can i change swap the values of i,j in swap2() function:

enter code here public class pass_by_ref {
        public static void swap(Integer i, Integer j)  //this will not change i j values in main 
        {
        Integer temp = new Integer(i);
        i = j;
        j = temp;
        }
        public static void swap2(Integer i, Integer j) 
        {
        i = 20;   //as i am setting i value to 20 why isn't it reflected in main and same for j
        j = 10;
        }
        public static void main (String[] args) throws java.lang.Exception
        {
        Integer i = new Integer(10);
        Integer j = new Integer(20);
        swap(i, j);
        System.out.println("i = " + i + ", j = " + j);
        swap2(i, j);
        System.out.println("i = " + i + ", j = " + j);
        }
        }

Outputs:

        i=10,j=20
        i=10,j=20;

I think that Integer i=new Integer(10) creates an object i with value 10,so when i write i=20;j=10 in swap2() i am setting there values!..so why isn't it working i know that swap() will not change i,j values but why isn't swap2() not working? Well what change to make in swap2() so that the values are swapped.

Najera
  • 2,869
  • 3
  • 28
  • 52
rashik
  • 19
  • 1
  • 3

1 Answers1

2

Java is always pass by value, and Integer is immutable and you can't update the callers reference. You can use an array (the values stored in an array are mutable). Because array is an Object, it's value is passed by the value of the reference to the array instance and you can thus modify the values in the array. Something like,

static void swap(int[] arr, int i, int j) {
    // error checking
    if (arr == null || i == j) {
        return;
    }
    if (i < 0 || j < 0 || i > arr.length - 1 || j > arr.length - 1) {
        return;
    }
    // looks good, swap the values
    int t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
}

and then you might call it like

public static void main(String[] args) {
    int[] arr = { 10, 20 };
    System.out.println(Arrays.toString(arr));
    swap(arr, 0, 1);
    System.out.println(Arrays.toString(arr));
}

And then (in the output) the values swap.

[10, 20]
[20, 10]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • ok thanks...But does "Integer i=new Integer(10) " creates an object or is it just like a primitive data type? – rashik Aug 21 '15 at 23:27
  • @rashik `Integer` is an immutable wrapper type in Java. Also, I believe that there is an instance pool in use to guarantee that `Integer(10)` == 10. – Elliott Frisch Aug 21 '15 at 23:28
  • A "funny" trick to swap 2 integers without using a third variable: a=a+b;b=a-b;a=a-b; – Laurent S. Aug 21 '15 at 23:39