static Keyword in Java Programming Langauge

Rumman Ansari   Software Engineer   2019-03-30   8598 Share
☰ Table of Contents

Table of Content:


The static keyword is used in java mainly for memory management. It is used with variables, methods, blocks and nested class. It is a keyword that are used for share the same variable or method of a given class. This is used for a constant variable or a method that is the same for every instance of a class. The main method of a class is generally labeled static.
No object needs to be created to use static variable or call static methods, just put the class name before the static variable or method to use them. Static method can not call non-static method.

In java language static keyword can be used for following

  • variable (also known as a class variable)

  • method (also known as a class method)

  • block

  • nested class

Static variable

  • If you declare any variable as static, it is known static variable.

  • A static variable is used for fulfilling the common requirement. For Example company name of employees, college name of students etc. Name of the college is common for all students.

  • The static variable gets memory only once in a class area at the time of class loading.

Advantage of static variable

Using static variable we make our program memory efficient (i.e it saves memory).

Understanding problem without static variable

class Employee{  
     int id;  
     String name;  
     String companyName="Google";  
}  

Suppose there are 500 employee in our office, now all instance data members will get memory each time when object is created.All employee have its unique id and name so instance data member is good.Here, companyName refers to the common property of all objects.If we make it static,this field will get memory only once.

Java static property is shared to all objects.

Syntax for declare static variable:

public static companyName;

Syntax for declare static method:

public static  void methodName()
{
.......
.......
}

Syntax for access static methods and static variable

className.variableName=10;
className.methodName();

Syntax for access static methods and static variable

className.variableName=10;
className.methodName();

Example of static variable

//Program of static variable

class Employee{
   int id;
   String name;
   static String companyName ="atnyla";

   Employee(int i,String n){
   id = i;
   name = n;
   }

 void display (){
	 System.out.println(id+" "+name+" "+companyName);
	 }

 public static void main(String args[]){
 Employee e1 = new Employee(12115,"Rahim");
 Employee e2 = new Employee(22313,"Ram");

 e1.display();
 e2.display();
 }
}

Output:

12115 Rahim atnyla
22313 Ram atnyla
Press any key to continue . . .

static method in java

Before going to static method we should know about instance method. Let's discuss about instance method

Instance methods which require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class in within which it defined.

public void displayMsg(String name)
{
 // code to be executed....
}
// Return type can be int, float String or user defined data type.

Memory allocation: These methods themselves are stored in Permanent Generation space of heap but the parameters (arguments passed to them) and their local variables and the value to be returned are allocated in stack. They can be called within the same class in which they reside or from the different classes defined either in the same package or other packages depend on the access type provided to the desired instance method.

Important Points:

  • Instance method(s) belong to the Object of the class not to the class i.e. they can be called after creating the Object of the class.
  • Every individual Object created from the class has its own copy of the instance method(s) of that class.
  • They can be overridden since they are resolved using dynamic binding at run time.
// Example to illustrate accessing the instance method .

class Dispaly{

    String name = "";

    // Instance method to be called within the same class or
    // from a another class defined in the same package
    // or in different package.
    public void displayMsg(String name){

        this.name = name;
    }
}

class MainClass {
    public static void main (String[] args) {

        // create an instance of the class.
        Dispaly obj = new Dispaly();

        // calling an instance method in the class 'displayMsg'.
        obj.displayMsg("atnyla");
        System.out.println(obj.name);
    }
}

Output:

atnyla
Press any key to continue . . . 

static methods in Java can be called without creating an object of class. Have you noticed why we write static keyword when defining main it's because program execution begins from main and no object has been created yet.

Some important points about static method

  • It is a method which belongs to the class and no need to create the object(instance)
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can call only other static methods and can not call a non-static method from it.
  • A static method can be accessed directly by the class name and doesn't need any object
  • Syntax : <class-name>.
  • A static method cannot refer to "this" or "super" keywords in anyway

main method is static , since it must be accessible for an application to run , before any instantiation takes place.

Java static method example program

Consider the example below to improve your understanding of static methods.

class MainClass {
  public static void main(String[] args) {
    displayMsg();
  }
 
  static void displayMsg() {
    System.out.println("Java programming language.");
  }
}

Output:

Java programming language.
Press any key to continue . . .

Java static method vs instance method

Instance method requires an object of its class to be created before it can be called while static method doesn't require object creation.

class MainClass {

  public static void main(String[] args) {
    displayMsg();  //calling without object
    MainClass t = new MainClass();
    t.showMsg();  //calling using object
  }

  static void displayMsg() {
    System.out.println("Programming is amazing.");
  }

  void showMsg(){
    System.out.println("Java is awesome.");
  }
}

Output:

Programming is amazing.
Java is awesome.
Press any key to continue . . .

Memory Allocation: They are stored in Permanent Generation space of heap as they are associated to the class in which they reside not to the objects of that class. But their local variables and the passed argument(s) to them are stored in the stack. Since they belong to the class so they can be called to without creating the object of the class.

Important Points:

  • The static method(s) are associated with the class in which they reside i.e. they can be called even without creating an instance of the class i.e ClassName.methodName(args).
  • They are designed with the aim to be shared among all Objects created from the same class.
  • Static methods can not be overridden. But can be overloaded since they are resolved using static binding by the compiler at compile time.

When to use static methods ??

  • When you have code that can be shared across all instances of the same class, put that portion of code into a static method.
  • They are basically used to access static field(s) of the class.

instance method vs Static method

  • An instance method can access the instance methods and instance variables directly.
  • An instance method can access static variables and static methods directly.
  • Static methods can access the static variables and static methods directly.
  • Static methods can’t access instance methods and instance variables directly. They must use a reference to object. And static method can’t use this keyword as there is no instance for ‘this’ to refer to.

static method of another classes

If you wish to call static method of another class then you have to write class name while calling static method as shown in example below.

import java.lang.Math;

class AnotherClass {
  public static void main(String[] args) {
    int result;

    result = Math.min(10, 20); //calling static method min by writing class name

    System.out.println(result);
    System.out.println(Math.max(10, 20));
  }
}

Output:

10
20
Press any key to continue . . .

Here we are using min and max methods of Math class, min returns minimum of two integers and max returns maximum of two integers. Following will produce an error:

min();

We need to write class name because many classes may have a method with same name which we are calling.

Important Example

// Example to illustrate Accessing the Static method(s) of the class.
import java.io.*;

class Display{

    public static String Name = "";

    public static void dispalayMsg(String name){

        Name = name;
    }
}

class MainClass {
    public static void main (String[] args) {

        // Accessing the static method dispalayMsg() and
        // field by class name itself.
        Display.dispalayMsg("atnyla");
        System.out.println(Display.Name);

        // Accessing the static method dispalayMsg() by using Object's reference.
        Display obj = new Display();
        obj.dispalayMsg("Rambo");
        System.out.println(obj.Name);


    }
}

Output:

atnyla
Rambo
Press any key to continue . . .