Java – are local variables in static methods also static?

I wonder if we declare them statically, all local variables will become static?

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 know, Java is always passed by value, but why does the state of X change after the changex call? Can anyone explain how Java handles static variables in memory allocation? What happens if we pass a static variable as an argument to a function (I know people don't usually do that)

Solution

The answer to most questions is "the same as any other variable"

Local variables in static methods are only local variables in static methods They are not static, they are not special

Static variables are stored in the memory connected to the corresponding class object; Any object referenced by a static reference variable can only exist in the regular heap

When a static variable is passed to a method as an argument, absolutely nothing interesting happens

About the situation in your code:

>Imagine that you have a toy balloon on a string (the balloon is your array object, and the string is a reference to the string declared in a()) > now you bind another string to the balloon and give the string to a friend (exactly what happens when you call the changex() method: the string is a parameter of the method, and it points to the same object. > Next, your friend pulls in the string, takes a black mark, and draws a face on the balloon (it's like modifying the changex () method of the array). > Then your friend doesn't know his string, just append your string to the balloon (the method returns, and the local variable in changex () is out of range.) > Finally, you roll up the string and look at the balloon: of course, you see the face (your a () routine sees the changed array.)

It's really simple!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>