-2

Assignment two arrays in a method receiving an array but contents of not changed,why

public class Sol {

    public static void main(String[] args) {
        int[] list = {1, 2, 3, 4, 5}; 
        reverse(list); 

        for (int i = 0; i < list.length; i++) 
            System.out.print(list[i] + " ");// here it prints after reversing 1 2 3 4 5 why?
}

public static void reverse(int[] list) {
     int[] array = new int[list.length];

     for (int i = 0; i < list.length; i++) 
         array[i] = list[list.length - 1 - i];
         list = array;  here is the problem // is it call by value  //here assignment why does not change the contents after exit from the method
i do not ask about call by reference and i do not need answers for the code
i need to understand this statement (list = array; why is it call by value when exiting from the method reversing disappeared)
     }
}

2 Answers2

0

Java is pass by value for primitive types and pass by reference for objects. Refer the below link for more details.

http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1

public static void main(String[] args) {
        int[] list = { 1, 2, 3, 4, 5 };

        list = reverse(list);

        for (int i = 0; i < list.length; i++)
            System.out.print(list[i] + " "); // here it prints after reversing 1 2 3 4 5 why? }
    }

    public static int[] reverse(int[] list) {

        int[] tempList = new int[list.length];

        for (int i = 0; i < list.length; i++)
            tempList[i] = list[list.length - 1 - i];

        return tempList;
    }
Bush
  • 261
  • 1
  • 11
0
int[] list = {1, 2, 3, 4, 5};

**reverse(list);**

for (int i = 0; i < list.length; i++)

System.out.print(list[i] + " ");// here it prints after reversing 1 2 3 4 5 why? }

public static void reverse(int[] list) {

int[] new List = new int[list.length];

for (int i = 0; i < list.length; i++)

new List[i] = list[list.length - 1 - i];

list = new List;}

}

In this After reversing the array you didnt assign the reversed array to any variable. that is the reason for this problem. Change like this and check it list = reverse(list);

Madhubala
  • 46
  • 1
  • 7