java - Method returning null is manipulating a final int array -
can please explain me why method returning null manipulating final int [] ?
final int [] vals = {2,3}; int [] vals2 = multiply(vals); for(int : vals) system.out.println(i); int [] multiply(int [] in){ for(int = 0; < in.length;i++){ in[i] *= 2; } return null; }
ouput:
4
6
edit:
have noticed behavior in methods returning array. same method returning int doesn't change original integers value...
full code:
public class main{ public main(){ int [] mylist = {56, 32, 200}; int [] newlist = mylist; bubble_sort(newlist); for(int : mylist){ system.out.println(i); } system.out.println(); for(int : newlist){ system.out.println(i); } } public int [] bubble_sort(int a[]){ int n = a.length; int [] s = a; (int = 0; < n ; i++){ (int j = n - 1; j >= (i+1); j--){ if (s[j - 1] > s[j]){ int t = s[j - 1]; s[j - 1] = s[j]; s[j] = t; } } } return null; // return s; } public static void main(string [] args){ new main(); } }
edit:
following code produces following output expected: 2, 4
int vals = 2; int vals2 = multiply(vals); system.out.println(vals); system.out.println(vals2); int multiply(int in){ return in*2; }
so question is, why method returning int not change input value, method returning array change inputs original value(s).
here, final
means vals
reference cannot changed referring initial array. says nothing whether contents of array can changed. see, can changed.
the final
keyword stop assigning array vals
, e.g.
vals = anotherarray; // disallowed; final
a solitary return null;
useless. multiply
method should have been declared void
, returning nothing.
Comments
Post a Comment