Can non-static methods modify static variables
No, any non-static method has access to static members. The only way this would be false is if the non-static context did not have access to the static member (ex. the static member is private to a class and the non-static code is not in that class). static variables exist to provide an instance free variable/method, so for example if we have a Game class and a highscore variable, the highscore would be static (accessible without an instance), and after every game (an instance of the Game class) completes we could alter the highscore from our non-static context if our score is greater than the high score.
Non-Static Methods can access both Static Variables & Static Methods as they Members of Class
Demo Code
public class Static_Class {
protected static String str;
private static int runningLoop;
static{
str = "Static Block";
}
/**
* Non-Static Method Accessing Static Member
*/
public void modifyStaticMember(){
str = "Non-Static Method";
}
/**
* Non-Static Method invoking Static Method
*/
public void invokeStaticMethod(){
String[] args = {};
if(runningLoop == 0){
runningLoop++;
main(args);
}
//Exiting as it will lead to java.lang.StackOverflowError
System.exit(0);
}
public static void main(String[] args) {
Static_Class instance = new Static_Class();
System.out.println(str);
instance.modifyStaticMember();
// Changed Value persists
System.out.println(str);
//Invoking Static Method
instance.invokeStaticMethod();
}
}
Non static methods can access static variables. Static methods can access only static variables or methods directly without creating object.ex:public static void main(String arg[])
I have found this from The Java Tutorials
- Instance methods can access instance variables and instance methods directly.
- Instance methods can access class variables and class methods directly.
- Class methods can access class variables and class methods directly.
- Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
So the answer is yes, non-static methods CAN modify static variables