Java program to Check the Accessibility of the Static and Non-Static Variables by a Static Method?

The static keyword is a non-access modifier in Java and can be used for variables, methods, and code blocks. A static variable in Java belongs to a class, that is, it is initialized only once at the beginning of execution. By using static variables, all instances of the class share a copy, and they can be accessed directly through the class name, without any instances. A static method also belongs to a class rather than an instance, it can only access static variables but not non-static variables.

Example 1: static methods can access static variables.

 

 
// Java program to check accessibility
// of static variables inside
// static methods

class GFG {

	// declaring variable 'a' as static
	static int a = 5;

	// main is also a static type
	public static void main(String args[])
	{

		// accessing value of
		// static variable
		System.out.println("Static variable:" + a);
	}
}

Output

Static variable:5

Example 2: We cannot access non-static variables inside a static method.

 

// Java program to check accessibility
// of non - static variables inside
// static methods

class GFG {

	// declaring variable 'a' as non - static
	int a = 5;

	// main is also a static type
	public static void main(String args[])
	{

		// accessing value of
		// non - static variable
		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 Program to demonstrate the accessibility
// of static and non-static variables
// by static method

class Student {

	// initialized to zero
	int a;

	// initialized to zero when class is loaded
	// but not for each object created.
	static int b;

	// Constructor
	Student()
	{

		// incrementing static variable b
		b++;
	}

	// method for printing
	public void printData()
	{
		System.out.println("Value of a = " + a);
		System.out.println("Value of b = " + b);
	}

	/*public static void increment(){
	a++;
	}*/
}

// Driver class
class GFG {

	// main is a static block
	public static void main(String args[])
	{

		// creating instance
		Student s1 = new Student();

		s1.printData();

		// directly accessing variable 'b'
		// by class name because it is static
		Student.b++;

		s1.printData();
	}
}

Output

Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2
 

Submit Your Programming Assignment Details