Here we consider two variables, one as static and other as non static. Now when we print the value of these variables in a static method, we get only the value of the static variable and an exception is generated while trying to print non static variable.
Here is the source code of the Java Program to Test whether a Static Method can Access the Static or Non-Static Variable. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class StaticMethod
static int a = 42;
int b = 99;
public static void main (String args)
System.out.println("static variable:" + a);
System.out.println("non static variable:" + b);
$ javac StaticMethod.java $ java StaticMethod static variable:42 Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - non-static variable b cannot be referenced from a static context
Sanfoundry Global Education & Learning Series – 1000 Java Programs.