STATIC KEYWORD IN JAVA

Static keyword in Java is mainly used when we want to access a class member without creating an instance of a class. Let us learn more about Static keyword in Java along with static variables, static methods, static blocks and nested static class.

Table of Contents

[hide]
  • What is Static Keyword in Java
  • Static variable in Java
  • Static Method in Java
  • Static Block in Java
  • Nested Static class in Java

What is Static Keyword in Java

Static Keyword in Java is used to write memory efficient programs. It saves memory and mainly used for memory management.

It can be used with Java variables, Java methods, Java blocks and Java nested class with a static keyword added to each of the following static member.

Usually, if you want to access class members, you create an instance of a class, and therefore access it with dot(.) operator, but sometimes we want to access class members directly without creating an instance of a class, then you should make a class members as static.

Java Keyword can be used with the following :

  • 1. Java class Variables
  • 2. Java class Method
  • 3. Java Block.
  • 4. Java Nested Class

Static variable

 static int name;

Static method

 static void play(){};

Static block

 static {
// some statements
}

Static inner class

class play{
  static class InnerStatic{
  }};

Let us learn about these concepts in detail.

Static Variable in Java

Any variable declared as static in Java is known as static variable. It is mostly used to fulfill the common properties.

Common properties may be indicated as Employees' Company Name, Students' College Name. The Static variable assigns memory only once to the class area at the time of class loading.

Advantage of Static keyword in Java : Static keyword in Java is used for memory management i.e it saves memory.

Java static and non-static Variables

copyimage
//Java Static vs non-static variables
class Employee { 
   int multiple = 20; // static variable
   static int result = 5; // non-static variable
} 
public class Codebator { 
  public static void main (String[] args) { 
      Employee obj = new Employee();

      // access the non-static variable with the help of object
      System.out.println("multiple * 5 = " + (obj.multiple * 5));

      // access the static variable directly
      System.out.println("result * 5 = " + (Employee.result * 5));
  } 
} 

OUTPUT :

multiple * 5 = 100result * 5 = 25 

In the above program we are using the non-static variable by creating an object of Employee class while we are accessing static variable directly with help of className.

When to use Static variable in Java ?

Let's take an example of IT employees, if we want to write a program to show the information about a specific company's 200 employees, then we have to create instance data members like name, EmployeId, which will get memory each time an object is created.

But since name and EmployeId is unique, the instance data member is fine. But if we want to display the company name for all the employees, then instance data member will take memory each time the object is created though company refers to the common property for all the employees.

Hence we can make the field static in this case, doing so it will take memory only once. Java static property is shared to all the objects.

Example : Static Variable in Java

copyimage
//Java Program to demonstrate the use of Static variable in Java
class Employee { 
 int EmpId;
 String name;
 static String Company_Name; //static variable

  // parameterized constructor with two arguments
  Employee(int i, String n) { 
     EmpId=i;
     name=n;
  } 

  //method to display employee details
  void show(){
     System.out.println(EmpId +" "+ name +" "+Company_Name); 
  }
} 
public class Codebator { 
  public static void main (String[] args) { 
    // passing arguments to the parameterized constructor
    Employee emp1 = new Employee(34023 ,"rajat" ); 
    Employee emp2 = new Employee(42002 , "sankalp"); 
    Employee.Company_Name = "Google";

    emp1.show();
    emp2.show();
  } 
} 

OUTPUT :

34023 rajat Google42002 sankalp Google 

Important Points to Remember :

  • Static variable in Java belongs to the class rather than an instance of a class.

  • Static variables in Java are initialized / get memory only once in the class area at the time of class loading.

  • The Java static property is shared with all objects or we can say all objects in Java share the single copy of static variable

  • You don't need to create an object to access the static variable. You can access it directly using the class name

  • Static variables can also be accessed by java instance methods.

Static Method in Java

Any method declared as static in Java is known as static method. They also belong to the class rather than an instance of a class.

Example : Static Method in Java

copyimage
//Java Program to demonstrate the use of Static method in Java
class Rectangle { 
   int length;
   int breadth;

   // non-static method
   public void recArea(int l, int b) {
	 System.out.println("non-static method area : "+ l*b);
   }

   // static method
   public static void getArea(int l, int b) { 
	 System.out.println("static method area : "+ l*b);
   } 
} 
public class Codebator { 
     public static void main (String[] args) { 
     Rectangle rec = new Rectangle(); 
     rec.recArea(20,70); // calling non-static method
     Rectangle.getArea(20, 30); // calling static method
  } 
} 

OUTPUT :

non-static method area : 1400static method area : 600 

Static Method can access the static variable or static data member and can modify the value of it.

Example 2 : Static Method in Java

copyimage
// Java Program to demonstrate the use of Static method in Java
class Employee { 
     int EmpId;
     String name;
     static String Company_Name; //static variable

     // parameterized constructor with two arguments
     Employee(int i, String n) { 
     EmpId=i;
     name=n;
     } 

     //static method in Java
     static void change(){  
     Company_Name = "Microsoft";  
     } 

     //method to display employee details
     void show(){
     System.out.println(EmpId +" "+ name +" "+Company_Name); 
     }
} 
public class Codebator { 
    public static void main (String[] args) { 
      // passing arguments to the parameterized constructor
      Employee emp1 = new Employee(34023 ,"rajat" ); 
      Employee emp2 = new Employee(42002 , "sankalp"); 
      Employee.Company_Name = "Google";
      Employee.change(); //calling static method
  
      emp1.show();
      emp2.show();
   } 
} 

OUTPUT :

34023 rajat Microsoft42002 sankalp Microsoft 

Important Points to Remember :

  • Static method in Java belongs to the class rather than an instance of a class.

  • All instance method must share a specific peice of common code.

  • Static Method definition cannot be overriden.

  • Static method should be used when your method does not use any instance variable, and the code does not depend on any instance creation.

Static Block in Java

A Static block in Java is mainly used for the static initialization of a class. The Static block consists of a series of statements that gets executed before the execution of main method. The Static Block is executed at the time of class laoding.

Example : Static Block in Java

copyimage
//Java Program to demonstrate the use of Static Block in Java
class StaticBlock { 
   static int count = 5;
  
   // static block
   static {
   count=count+5;
   System.out.println("This is static block");
   }
} 
public class Codebator { 
  public static void main (String[] args) { 
     System.out.println(StaticBlock.count);
  } 
} 

OUTPUT :

This is static block10 

Static Blocks are executed before the execution of constructor , the example can be seen below.

Example : Static Block Executed before Constructor

copyimage
//Java Program to demonstrate the use of Static Block in Java
class StaticBlock { 
   static int count = 5;
  
   // constructor
   StaticBlock(){
   System.out.println("Constructor called");
   }

   // static block
   static {
   count = count+5;
   System.out.println("This is static block");
   }
} 
public class Codebator { 
  public static void main (String[] args) { 
     StaticBlock s1 = new StaticBlock();
     StaticBlock s2 = new StaticBlock();
  } 
} 

OUTPUT :

This is static blockConstructor called Constructor called 

If there are multiple static blocks, then the execution of the blocks are made from top to bottom.

Example : Multiple Static blocks in Java

copyimage
//Java Program to demonstrate the use of Multiple Static Block in Java
class StaticBlock { 
   static int count = 5;

   // static block
   static {
   count = count+5;
   System.out.println("This is static block 1");
   }
   
   // static block
   static {
   count = 40;
   System.out.println("This is static block 2");
   }
} 
public class Codebator { 
  public static void main (String[] args) { 
      System.out.println(StaticBlock.count);
  } 
} 

OUTPUT :

This is static block 1This is static block 2 40 

Important Points to Remember :

  • A Static block in Java is used for the static initialization of a class or data members.

  • A Static Block is always executed before the execution of main method in Java.

  • Static Method is executed at the time of class loading

  • Static Blocks are executed before the execution of the constructors.

Nested Static class in Java

A Static class is created inside the class that cannot access non-static data members and methods. A Static class can access static members of the outer class including private.

Example : Nested Static class in Java with instance method

copyimage
//Java Program to demonstrate the use of Nested Static Class in Java
class Outside { 
   static int count = 5;
   static class Inside {
       void count() {
       System.out.println("Value of count is " + count);
       }
   }
} 
public class Codebator { 
   public static void main (String[] args) { 
       Outside.Inside obj = new Outside.Inside();
       obj.count();
    } 
} 

OUTPUT :

Value of count is 5

In the above program we need to create an instance of static nested class because it contains instance method count(). But we do not need to create an instance of outer class beacuse nested class is static and can be accessed without object.

Example : Nested Static class in Java with static method

copyimage
//Java Program to demonstrate the use of Nested Static Class in Java
class Outside { 
   static int count = 5;
   static class Inside {
       static void count() {
       System.out.println("Value of count is " + count);
       }
   }
} 
public class Codebator { 
   public static void main (String[] args) { 
       Outside.Inside.count();
    } 
} 

OUTPUT :

Value of count is 5

Since we have used the static method in the inner nested static class, hence we do not need to create an instance of inner class. We can now access it directly since static properties, methods or classes can be accessed without object.