How to Check the Accessibility of the Static and Non-Static Variables by a Static Method?
Last Updated :
16 Jun, 2021
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.
Example 1: static methods can access static variables.
Java
class GFG {
static int a = 5 ;
public static void main(String args[])
{
System.out.println( "Static variable:" + a);
}
}
|
Example 2: We cannot access non-static variables inside a static method.
Java
class GFG {
int a = 5 ;
public static void main(String args[])
{
System.out.println( "Non - Static variable:" + a);
}
}
|
Output
prog.java:16: error: non-static variable a cannot be referenced from a static context
System.out.println("Non - Static variable:" + a);
^
1 error
Example 3:
Java
class Student {
int a;
static int b;
Student()
{
b++;
}
public void printData()
{
System.out.println( "Value of a = " + a);
System.out.println( "Value of b = " + b);
}
}
class GFG {
public static void main(String args[])
{
Student s1 = new Student();
s1.printData();
Student.b++;
s1.printData();
}
}
|
Output
Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2
In the above program if we remove comments of the increment method then an error will be raised because the increment method is static and variable a is non-static and we already know static methods cannot access non – static variables.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...