Are local variables in static methods also static?

java, memory-management, static, static-methods

Solution

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!

Problem

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)

Original source