Saturday, 3 February 2018

java - Why when I pass an array, it changes value in the method? Amazing




public class Test {
public static void main(String[] args) {
int[] arr = new int[5];
arr[0] = 1;
method(arr);
System.out.println(arr[0]);
}

private static void method(int[] array)
{
array[0] = 2;
}
}


After invoking method, arr[0] becomes 2. Why is that!?


Answer



You can call set methods on objects passed to a method. Java is pass by value, which means that you can't replace an object in a method, though you can call set methods on an object.



If Java were pass by reference, this would pass:



public class Test {

public static void main(String[] args) {
Test test = new Test();
int j = 0;
test.setToOne(j);
assert j == 1;
}

public void setToOne(int i) {
i = 1;
}
}

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...