Home / Programs / static Method and variable in java, how to access methods and variables
🚀 Programming Example

static Method and variable in java, how to access methods and variables

👁 1,132 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

💻 Program Code

 /*
 * 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();
 }
}

                        

🖥 Program Output

Inside Static method
10
10
Inside Static method
Press any key to continue . . .
                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

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.

🔥 Practice suggestion

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.