static keyword -


static can be variables, methods and only inner classes.

static variables -

static variables are common to all objects i.e. we cannot create separate copies of static variables for objects.

Example -

class Test
{
    private int a = 0;
    private static int b = 0;
    
    public Test()
    {
        a++;
        b++;
    }
    public void setA(int x)
    {
        a = x;
    }
    public void setB(int y)
    {
        b = y;
    }
    public void disp()
    {
        System.out.println(a+"   "+b);
    }
}

public class Call {

    public static void main(String[] args) {

        Test t1 = new Test();
        t1.disp();
        Test t2 = new Test();
        t2.disp();
        Test t3 = new Test();
        t3.disp();
 
        t1.setB(10);
        t1.disp();
        t2.disp();
        t3.disp();
        
    } 
}

 

Output -

     1   1
     1   2
     1   3
     1   10
     1   10
 
Here we have two variables a and b, and 3 objects t1, t2 and t3. As b is static so it will be common for all the three objects, whereas there will be separate copy of a for each object.
When the statement Test t1 = new Test(); gets executed an object t1 will created and it will call default constructor of Test class and value of a and b will be incremented by 1. So the statement t1.disp(); will print the output - 1 1
Next the statement Test t2 = new Test(); gets executed and same process follows but now value of a will be 1 and value of b will be 2, because there will be separate copy of a for t2 object, so it will incremented to 1, but b is common for all objects and its value is already incremented to 1 by t1 object so now when it will increment by t2 object, it will becomes 2.

so the statement t2.disp(); will print the output ? 1 2.
Next a third object t3 is created and same process follows and t3.disp(); will print the output - 1 3.
Next t1 has changed the value of b to 10. So it will be changed for every object. So if we again print the values of t1, t2 and t3 objects they all going to have the same value 10 for variable b.

static methods -

We can access static methods without creating any object by using class name directly. Always remember that within static methods we can only have static members.

Example -

class Test
{
    private int a = 0;
    private static int b = 0;
    
    public Test()
    {
        a++;
        b++;
    }
    public void setA(int x)
    {
        a = x;
    }
    public void setB(int y)
    {
        b = y;
    }
    public void disp()
    {
        System.out.println(a+"   "+b);
    }
   static public void show()
    {
        System.out.println(b);  // we cannot access a here.
    }
}
public class Call {

    public static void main(String[] args) {

        Test t1 = new Test();
        t1.disp();
        Test.show();   // calling static method by class name
    } 
}

         

Output -

             1      1
             1