Static Keyword

Static

Static is a keyword in java language which is used to allocates the sufficient memory space for the class variables.In java language these are classified into following types
  • Static variable
  • Static method
  • Static Block
  • Static variable

    if any variable preceded by static keyword is known as static varable.

    Syntax: static int x=10

        class Demo
        {
        int x; //  x is a instance variable
        static int y; // y is a class variable
        // here x,y are the  Global variables
        void show(int z) // z is formal variable
        {
        int p;  // p is a local variable
        if()
        {
        int q; // q is a block variable
        }
        }
        }
        
    

    Static Method

    If any method preceded by static keyword is known as static method.
    Syntax:
    static returntype methodname(list of parameters/no parameters)
    {
    ...
    ...
    }
    class Demo
    {
    int x=10;  //non static variable
    static int y=20; // static variable
    
    void show()
    {
    System.out.println(x); // You get output
    System.out.println(y); // You get output
    }
    static void disp()
    {
    //System.out.println(x);  // You get error
    //because static mentods can not accept  non static variables
    System.out.println(y);  // You get output
    }
    }
    class MM
    {
    public static void main(String args[])
    {
    Demo d=new Demo();
    d.show(); // You get output
    d.disp(); // You get output
    System.out.println(d.x); // You get output
    System.out.println(d.y); // You get output
    
    //Note: By using object we have to call all static and non static variables and methods
    
    //Demo.show();
    Demo.disp();  // You get output
    //System.out.println(Demo.x); // You get error
    System.out.println(Demo.y);  // You get output
    
    //Note: By using class we have to call static methods only
    }
    }
    
    
    
        
    

    Static Block

    Static block is used to execute a program without using main method.
    Syntax:
    static
    {
    ...
    ...
    }
    class Main
    {
    static
    {
    System.out.println("Welcome");
    System.exit(0);
    }
    }
    
    
    Note:
    It is not available in latest versions(It works only java 6 before versions).
    FOr more Programs Click Here