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 Class
objects; 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:
- Imagine that you have a toy balloon on a string (the balloon is your array object, and the string is the reference to it declared in
A()
.)
- Now you tie another string on to the balloon and hand that string to a friend (that's exactly what happens when you call the
changeX()
method: the string is the parameter of the method, and it points to the same object.)
- Next, your friend pulls in the string, takes a black marker and draws a face on the balloon (this is like the
changeX()
method modifying the array).
- Then your friend unties his string, leaving just your string attached to the balloon (the method returns, and the local variable in
changeX()
goes out of scope.)
- Finally you reel in the string and look at the balloon: of course, you see the face (your
A()
routine sees the changed array.)
It's really as simple as that!
As others have pointed out, the variables which are local to a METHOD are the same as any other variable declared within any other method -- they are dynamically allocated and may be freed when the method returns the the variable is no longer visible.
However, if you need static variables, you would have to declare them outside the methods, as ordinary static variables for a class. If, by convention, you leave them alone except when inside that particular method, they have the same effect as if they were static and local to the method. Just be sure to add comments to that effect.
Static variables are stored in a special area of the heap called the "permanent generation".
Local variables delcared in a static method do not make any difference with those declared in a non-static method. Object references and primitive variables are placed on the stack.Whenever you create an object, the storage is allocated on the heap when that code is executed.