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.



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.