What is the output of the following code?
public class Main { public static void main(String[] args) { int x = 1; // x represents an int value int[] y = new int[10]; // y represents an array of int values m(x, y); // Invoke m with arguments x and y System.out.println("x is " + x); System.out.println("y[0] is " + y[0]); }/*w w w .java 2 s . com*/ public static void m(int number, int[] numbers) { number = 1001; // Assign a new value to number numbers[0] = 5555; // Assign a new value to numbers[0] } }
x is 1 y[0] is 5555
Why after m is invoked, x remains 1, but y[0] become 5555.
When m(x, y) is invoked, the values of x and y are passed to number and numbers.
Since y contains the reference value to the array, numbers now contains the same reference value to the same array.
The following code gives another program that shows the difference between passing a primitive data type value and an array reference variable to a method.
The program contains two methods for swapping elements in an array.
The first method, named swap()
, fails to swap two int arguments.
The second method, named swapFirstTwoInArray()
, successfully swaps the first two elements in the array argument.
public class Main { public static void main(String[] args) { int[] a = {1, 2}; // Swap elements using the swap method System.out.println("Before invoking swap"); System.out.println("array is {" + a[0] + ", " + a[1] + "}"); swap(a[0], a[1]);// w ww .ja v a 2s . c om System.out.println("After invoking swap"); System.out.println("array is {" + a[0] + ", " + a[1] + "}"); // Swap elements using the swapFirstTwoInArray method System.out.println("Before invoking swapFirstTwoInArray"); System.out.println("array is {" + a[0] + ", " + a[1] + "}"); swapFirstTwoInArray(a); System.out.println("After invoking swapFirstTwoInArray"); System.out.println("array is {" + a[0] + ", " + a[1] + "}"); } /** Swap two variables */ public static void swap(int n1, int n2) { int temp = n1; n1 = n2; n2 = temp; } /** Swap the first two elements in the array */ public static void swapFirstTwoInArray(int[] array) { int temp = array[0]; array[0] = array[1]; array[1] = temp; } }