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)
A static variable can be either a global or local variable. Both are created by preceding the variable declaration with the keyword static.
In many languages, global variables are always static, but in some languages they are dynamic, while local variables are generally automatic, but may be static.
Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods. However, non-static methods have access to all variables (instance or static) and methods (static or non-static) in the class.
The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the variable is created and shared among all objects at a class level.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With