2

i saw this Heap Sort program on geeksForGeeks: https://www.geeksforgeeks.org/heap-sort/

in main method(), they've taken an int[] and passed it to sort(). After that they passed the same int[] to a utility function printArray() for printing and it prints the sorted array . I tried the same to swap 2 variables, but it doesnt work .

public void swap(int a,int b){
int t=a;
a=b;
b=t;
}
public static void printVal(int a,int b){
System.out.println("New value \n a: "+a+", b: "+b);
}
public static void main(String[] args) {
    ArrayEx ae= new ArrayEx();
    int a=5;
    int b=10;
    System.out.println("Old value \n a: "+a+", b: "+b);
    ae.swap(a, b);
    printVal(a,b);
}

can anyone please tell how argument passing and processing works in java ?

Thanks in advance

Bhardwaj Joshi
  • 401
  • 4
  • 3
  • The difference comes down to the fact that int is a primitive type whereas int[] is a reference type. – Zachary Dec 30 '17 at 03:04

1 Answers1

0

Swapping

The observation in the question is that with int[] you are able to swap the values and have any reference to the same Object preserve the changes while swapping int does not.

public void swap(int a,int b) {
    int holder = a;
    a = b;
    b = holder;
}

public void swap(int[] arr, int a, int b) {
    int holder = arr[a];
    arr[a] = arr[b];
    arr[b] = holder;
}

A variable referencing int[] references the Object in memory, so modifying the Object itself will result in any reference to the identical Object preserving changes. However, in the example with int you are changing the value that is being referenced to. This will result in the variable referencing another primitive value, in which the only change is to that specific primitive variable. You are not changing any values, just referencing another one.

Simply put, modifications made to an Object will be preserved as you physically change the Object in memory, and any reference to that Object will observe the changes.

Zachary
  • 1,693
  • 1
  • 9
  • 13