/*
* Here we will learn to access Static method and Static Variable.
*/
public class JavaStaticExample {
static int i = 10;
static void method() {
System.out.println("Inside Static method");
}
public static void main(String[] args) {
// Accessing Static method
JavaStaticExample.method();
// Accessing Static Variable
System.out.println(JavaStaticExample.i);
/*
* No Instance is required to access Static Variable or Method as we
* have seen above. Still we can access the same static variable and
* static method using Instace references as below.
*/
JavaStaticExample obj1 = new JavaStaticExample();
JavaStaticExample obj2 = new JavaStaticExample();
/*
* Accessing static variable in Non Static way. Compiler will warn you
* with below warning.
*
* The static field JavaStaticExample.i should be accessed in a static
* way.
*/
System.out.println(obj1.i);
// Accessing satic method using reference.
// Warning by compiler
// "The static method method() from the type JavaStaticExample should be accessed in a static way"
obj1.method();
}
}
Inside Static method
10
10
Inside Static method
Press any key to continue . . .
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.