static keyword in Java

static keyword in Java

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

static members

Instance variables and methods are associated with and accessed through an instance of the class (i.e., through a particular object). In contrast, members that are declared with the static modifier live in the class and are shared by all instances of the class. Variables declared with the static modifier are called static variables or class variables; similarly, these kinds of methods are called static methods or class methods.

The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. The static variable gets memory only once in class area at the time of class loading.static keyword saves memory reasources and make program more efficient.

Without static variable


class Employee
{  
     int emp_no;  
     String name;  
     String department="IT";  
}  
  
Suppose there are 1000 employees in my department, now all instance data members will get memory each time when object is created.All employee have its unique emp_no and name so instance data member is good.Here, department refers to the common property of all objects.If we make it static,this field will get memory only once.

Example of static variable

Program


class Employee
{  
   int emp_no;  
   String name;  
   // department is static variable so it will allocate
   //memory only once at compile time
   static String department ="IT";  
     
   Employee(int e,String n)
   {  
        emp_no = e;  
        name = n;  
   }  
    void display ()
    {
        System.out.println("emp_no " + emp_no + " department = " + department);
    }  
}

public class Main
{
     public static void main(String args[])
     {  
         Employee e1 = new Employee(111,"raj");  
         Employee e2 = new Employee(222,"aditya");  
         e1.display();  
         e2.display();  
     }  
}  
  
  

Output


emp_no = 111 department = IT
emp_no = 222 department = IT
  

Explanation

Static members can be accessed like instance members. Inside our class, we can refer to it like any other variables.However, since static members exist in the class itself, independent of any instance, we can also access them directly through the class. We don’t need a object to get or set the variable; instead, we can use the class to select the variable.

Program


public class Main
{
    //initialize counter variable
    static int counter = 0;
    
    Main()
    {
        counter++;
    }
    
    public static void main (String[] args) 
    {
        new Main();
        new Main();
        new Main();
        new Main();
        // accessing static member through classname
        System.out.println(Main.counter);
    }
}
  
  

Output


4
  

Explanation

In this example, we have created an instance variable named counter which is incremented in the constructor. Since this is variable so gets the memory at the compile time , each object is sharing the instance variable, if it is incremented, it will reflect to other objects. So each objects will increment the value of shared variable in the counter variable.Static variables are, essentially, global variables.
We can create static variables at class-level only.see below code:

class Main
{
   public static void main(String args[]) 
   { 
        System.out.println(fun());
   }
   static int fun()
   {
       //static variables are allowed at class level only
        static int x= 10;  //Error: Static local variables are not allowed
        return x--;
   }
} 
  

Explanation

The above code will give the error.

static block

static block and static variables are executed in order they are present in a program.

Program


// static blocks and variables
class Main
{
    // static variable
    static int a = m1(); // 2
     
    // static block
    static // 5
    {
        System.out.println("We are inside static block"); // 6
    }
     
    // static method
    static int m1() // 3
    {
        System.out.println("We are inside method m1"); .// 4
        return 20; // 7
    }

    // static main method
    public static void main(String[] args)
    {
       System.out.println("Value of a : "+ a); // 1 // 9
       System.out.println("We are inside main method"); // 8
    }
}
  
  

Output


We are inside method m1
We are inside static block
Value of a : 20
We are inside main method
  

static methods

When a method is declared with static keyword, it is known as static method. The most common example of a static method is main( ) method.As discussed above, Any static member can be accessed before any objects of its class are created, and without reference to any object.Methods declared as static have several restrictions:
  1. They can only directly call other static methods.
  2. They can only directly access static data.
  3. They cannot refer to this or super in any way.

Program


class cl
{
    int a = 10;
}

// java program to demonstrate restriction on static methods
class Test extends cl
{
    // static variable
    static int a = 10;
     
    // instance variable
    int b = 20;
     
    // static method
    static void m1()
    {
        //method m1 is static so it can access it and modify it
        a = 20;
        System.out.println("inside m1");
         
         // Cannot make a static reference to the non-static field b
         b = 10; // compilation error
                 
         // Cannot make a static reference to the 
        // non-static method m2() from the type Test
         m2();  // compilation error
          
         //  Cannot use super in a static context
         System.out.println(super.a); // compiler error 
    }
     
    // instance method
    void m2()
    {    
        System.out.println("from m2");
    }

    public static void main(String[] args)
    {
        // main method 
    }
}
  
  

Output


Main.java:23: error: non-static variable b cannot be referenced from a static context
         b = 10; // compilation error
         ^
Main.java:27: error: non-static method m2() cannot be referenced from a static context
         m2();  // compilation error
         ^
Main.java:30: error: non-static variable super cannot be referenced from a static context
         System.out.println(super.a); // compiler error
                            ^
3 errors
  
extends keyword which is used in above program we will learn about this when we see inheritance.

static final variable in Java

In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.Such behavior is obvious as static variables are shared among all the objects of a class; creating a new object would change the same static variable which is not allowed if the static variable is final.

Program


class Main
{
    //since this variable is not static
    final int a;
    Main()
    {
        //it can be initialize by constructor
        a = 10;
    }

    public static void main(String args[]){}
}
  
  

Explanation

The above program works fine but if variable is static final it can not be initialized by constructor.see program below...

Program


class Main
{
    //since this variable is static
    static final int a;
    Main()
    {
        //it can not be initialize by constructor
        a = 10;
    }

    public static void main(String args[]){}
}
  
  

Output


Main.java:8: error: cannot assign a value to final variable a
        a = 10;
        ^
1 error
  

Why java main method is static ?

Main method in Java is entry point for any core Java program. In core Java program, execution starts from main method when you type java main-class-name, JVM search for public static void main(String args[]) method in that class and if it doesn't find that method it throws error NoSuchMethodError:main and terminates.

Now come to the main point "Why the main method is static in Java", there are quite a few reasons around but here are few reasons which make sense to me:

1. Since the main method is static Java virtual Machine can call it without creating any instance of a class which contains the main method.

2. If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.

3. Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.

difference of static keyword in c++ and Java

Static keyword is used for almost same purpose in both C++ and Java. There are some differences though.

1. Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initialization of a class. The code inside static block is executed only once. See Static blocks in Java for details.

2. Unlike C++, Java doesn’t support static local variables.

Comments

Popular posts from this blog

System.Environment

System.Console

Datatype and keyword