When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.
Important points for static variables:
- We can create static variables at class-level only. See here
- static block and static variables are executed in order they are present in a program.
Below is the java program to demonstrate that static block and static variables are executed in the order they are present in a program.
// Java program to demonstrate execution // of static blocks and variables class Test { // static variable static int a = m1(); // static block static { System.out.println("Inside static block"); } // static method static int m1() { System.out.println("from m1"); return 20; } // static method(main !!) public static void main(String[] args) { System.out.println("Value of a : " + a); System.out.println("from main"); } } |
from m1 Inside static block Value of a : 20 from main
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Static and non static blank final variables in Java
- Difference between static and non-static variables in Java
- Understanding storage of static methods and static variables in Java
- Internal static variable vs. External static variable with Examples in C
- Difference between static and non-static method in Java
- Why non-static variable cannot be referenced from a static method in Java
- Understanding "static" in "public static void main" in Java
- Are static local variables allowed in Java?
- Assigning values to static final variables in Java
- Initialize a static map in Java with Examples
- Static and Dynamic data structures in Java with Examples
- Atomic Variables in Java with Examples
- Shadowing of static functions in Java
- Comparison of static keyword in C++ and Java
- Static blocks in Java
- Static class in Java
- Static vs Dynamic Binding in Java
- Static methods vs Instance methods in Java
- static keyword in java
- Final static variable in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

