Please Explain this Java Array Reference Parameter Passing Behavior -


public class testarray {     public static void main(string[] args) {         int[] ar = {1,2,3,4,5,6,7,8,9};          shiftright(ar);         (int = 0; < ar.length; i++) {             system.out.print(ar[i]);         }         // prints: 912345678 --         system.out.println();          reversearray(ar);         (int = 0; < ar.length; i++) {             system.out.println(ar[i]);         }         // prints: 91234567 -- don't understand                system.out.println();            }     public static void shiftright(int[] ar) {         int temp = ar[ar.length - 1];         (int = ar.length - 1; > 0; i--) {             ar[i] = ar[i - 1];         }         ar[0] = temp;     }     public static void reversearray(int[] ar) {         int[] temp = new int[ar.length];         (int = 0, j = temp.length - 1; < ar.length; i++, j--) {             temp[i] = ar[j];         }         ar = temp;         (int = 0; < ar.length; i++) {             system.out.print(ar[i]);         }         // prints: 876543219         system.out.println();     } } 

passing array parameter results in passing reference array parameter; if array parameter changed within method, change visible outside of method.

the first method, shiftright, expect to: changes array outside of method.

the second method, however, not change array outside of method. running loop inside of method prints correct values. why isn't reference of ar pointed temp? because variable temp destroyed when method stops--does kill reference well? if case, why java take ar, pointed reference of temp , reapply the original reference of ar?

thank you.

in java, it's misnomer objects passed reference. it's more accurate reference object passed value.

you pass array reference reversearray value. local parameter copy of reference array. later when say

ar = temp; 

you have pointed local ar temp, not original array reference ar main.

on other hand, in shiftright method, have directly accessed array through copied reference, original array's contents change , method works expected.


Comments