A static method belongs to the class rather than the object of a class. It can be invoked without the need for creating an instance of a class. It can access static data member and can change the value of it.
The static keyword is a non – access modifier in Java which can be used for variables, methods, and block of code. Static variables in Java belong to the class i.e it is initialized only once at the start of the execution. By using static variables a single copy is shared among all the instances of the class, and they can be accessed directly by class name and don’t require any instance. The Static method similarly belongs to the class and not the instance and it can access only static variables but not non-static variables.
prog.java:16: error: non-static variable k cannot be referenced from a static context System.out.print("value of a is: " + k); ^ 1 error
The instance variable, as the name suggests we need an instance of a class. We cannot access directly instance variables from a static method. Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.
Example 2 :
Value of k is: 10
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.