I am wondering do all the local variables become static if we declare them in a static method ?
for example:
public static void A(){
int x [] = {3,2};
changeX(x);
for (int i = 0; i< x.length; i++){
System.out.println(x[i]); // this will print -1 and 1
}
}
private static void changeX(int[] x){
x[0] = -1;
x[1] = 1;
}
As far as I understand that Java is pass by value always, but why the state of X has changed after we made the changeX call ? Can anyone explain that please ? and can anyone explains how does Java deal with static variables in terms of memory allocation ? and what happen if we pass a static variable to a function as a parameter (I know people won’t normally do that)
The answer to most of your questions is “the same as any other variable.”
Local variables in static methods are just local variables in a static method. They’re not static, and they’re not special in any way.
Static variables are held in memory attached to the corresponding
Classobjects; any objects referenced by static reference variables just live in the regular heap.When you pass a static variable to a method as an argument… absolutely nothing interesting happens.
Regarding the scenario in your code:
A().)changeX()method: the string is the parameter of the method, and it points to the same object.)changeX()method modifying the array).changeX()goes out of scope.)A()routine sees the changed array.)It’s really as simple as that!