Thursday, September 4, 2025
HomeLanguagesJavaStatic Variables in Java with Examples

Static Variables in Java with Examples

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");
    }
}


Output:

from m1
Inside static block
Value of a : 20
from main
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS