java - Need Assistance Understanding execution of Program -
i reviewing practice problem , want know sequence how program came answer of ---> 2 1 having trouble understanding main driver call. understand usage of methods.
the code is:
public class test { public static void main(string[] args) { int[] x = {1, 2, 3, 4, 5}; increase(x); int[] y = {1, 2, 3, 4, 5}; increase(y[0]); system.out.println(x[0] + " " + y[0]); } public static void increase(int[] x) { (int = 0; < x.length; i++) x[i]++; } public static void increase(int y) { y++; } }
the code demonstrating difference between (effectively) call-by-reference (in first increase method) , call-by-value (in second increase method). in fact, both methods use call-by-value, in first case value reference object (the array) , in second case int (a single value array).
the code int[] x = {1, 2, 3, 4, 5} creates array. when call increase(x) calling first increase method. method iterates through elements of array , increments each one. line x[i]++ equivalent x[i] = x[i] + 1. results stored array. end of call, array contains {2, 3, 4, 5, 6}. hence x[0] 2.
in second call increase(int y) not pass in array, value of y[0] (i.e. 1). method increments variable y has no effect outside of method. in java, when pass variable passed value means copy of value passed in. changes made value not affect original.
when pass in array, pass reference array object. reference cannot changed, contents of object (the contents of array) can changed.
i have admit bit confusing, re-read i've written few times , you'll it!
Comments
Post a Comment