Possible Duplicate : Is Java “pass-by-reference” or “pass-by-value”?
i am trying to do initialization of an array in this way -
class Main {
public static void main(String[] args) {
int n = 4;
int[] s = null;
int[] f = null;
init(n, s, f);
System.out.println(s.length);
}
public static void init(int n, int[] s, int[] f) {
s = new int[n];
f = new int[n];
}
}
but i am getting NullPointerException
for the s.length
. so this clear passing the parameter to another method is pass by value. therefor objects are not initialize.
but when i do swap in to value in a different method then this is working. like -
class Main {
public static void main(String[] args) {
int n = 4;
int[] s = new int[n];
int[] f = new int[n];
s[0] = 10;
f[0] = 20;
System.out.println(s[0] + " " + f[0]);
swap(s, f);
System.out.println(s[0] + " " + f[0]);
}
public static void swap(int[] s, int[] f) {
int t = s[0];
s[0] = f[0];
f[0] = t;
}
}
on the other hand this isn't swap values.
class Main {
public static void main(String[] args) {
Integer a = 10;
Integer b = 20;
swap(a , b);
System.out.println(a + " " + b);
}
public static void swap(Integer a, Integer b) {
int t = a;
a = b;
b = t;
}
}
therefor i need some explanation whether java “pass-by-reference” or “pass-by-value”? this explanation could help me to understand why it is not possible to create object in another method.
sorry for my bad English. thanks in advance.