Java Static keyword

Java Static Keyword

Java Static Keyword

Static keyword in java is widely used in application. In this tutorial, we will discuss about static keyword, how can you implement it in you application, where it can be used and what is the impact of using this keyword.

Java Static Keyword
Java Static Keyword


Static Keyword

static is a keyword provided by Java. The main purpose of static keyword is to save memory area. In our application, memory management is very important which provides great performance. In some cases, we need to avoid unnecessary object creation. That can be solved by static keyword.

Some important things about static keyword.
  1. static keyword is mainly used to save memory.
  2. static keyword can be used with data members, inner classes, methods.
  3. static variables are class level variables.
  4. A separate area is created in “Class Area” for static variables.
  5. Static variables can be used to create common property. Which will be shared by each and every object in java program.
  6. When used with methods, you can access it via class name and that method can not be overridden.
  7. You can not create local static variable. Only instance variables can be static.
  8. Static instance initializer block can be used to initialize static instance variables.
  9. each object shares the common memory area for static variables. If you update static variable, every object will use that updated value. So, make static variables carefully.
  10. Java static initializer block is executed before main method during class loading.

Let’s understand static keyword with real scenario.

You have given a task where you have been told to create a separate class which is be shared to each developer in the company. This class will only contain constant variables, and developers will use these constants later in their projects. You have been instructed that your class should be memory efficient.

Now you have two things in your mind, class will only have constant variables and it should be memory efficient. What will you do now ?

Let’s create a GlobalConstants class for you.

class GlobalConstants {
      public static final LOGIN_SUCCESS_MESSAGE = "You have been logged out.";
}

class Demo {
      public static void main(String arg[]) {
             System.out.println("Login Message : " + GlobalConstants.LOGIN_SUCCESS_MESSAGE);
      }
}

Let’s discuss what’s happening in above example.

We have created a separate class called “GlobalConstants” which will only contains constants variables. Then we have created a constant variable called “LOGIN_SUCCESS_MESSAGE”. But how it becomes constant ?. You can make constant variable by using “final” keyword. “final” ensures that nobody can modify it’s value once initialized (We will discuss Final keyword later). 

As for now, we have created separate class for constant variables and we have defined a variable as well which will be used by developers later. 

But now, how to make it memory efficient. And there comes “static” variable in picture. Static variable will do the following things :

  • You are using static with instance variable, so you don’t need to create separate object just to access the variable.
  • You will be able to access the variable value by class name itself.
  • When you don’t need to create objects then your class will be memory efficient.

Where we can use static keyword

You can use static keywords with methods, instance variables, inner classes. Let’s discuss each of them in details with examples.

Static with variables

Static keyword can be used with the instance variables. When you use static with variables, each object will share the same value which saves the memory area. A separate area will be created in “Class Area” for static instance variables. If one object will modify the value then it will be reflected in other objects as well.

Let’s take an example.

class Company {
      private int empId;
      private String employeeName;
      private static String CompanyName = "Company";

      public Company(int empId, String empName) {
             this.empId = empId;
             this.employeeName = empName;
      }

      public void getEmployeeInfo() {
             System.out.println("Id : " + this.empId + ", Name : " + this.employeeName + ", Company Name : " + CompanyName);
      }

      public static void main(String arg[]) {
             Company c = new Company(2012, "Ashish");
             Company d = new Company(2013, "John");
 
             c.getEmployeeInfo();
             d.getEmployeeInfo();
      }
}

output :
Id : 2012, Name : Ashish, Company Name : Company
Id : 2013, Name : John, Company Name : Company

Look at he above example, no matter how many objects you create. The value of the static variable will be the same for each object.

Static with methods

You can use static keyword with methods as well. When you apply static to method, that means you can access that method without creating any object. That method now belongs to the class rather than the object of that class. You will be able to access that method via class name (If method is public). 

Remember,

Static methods can only access static instance variables. If you will try to use non static field inside static method, you will get error at that time.

You can not use this or super keyword inside static methods because static belongs to class not instance of that class.

 static methods can not be overridden. We will discuss about overriding later. For now, just remember, overriding is a concept in which child class inherit base class methods to provide their own definition.

Example

class Company {
   private int empId;
   private String employeeName;
   private static String CompanyName = "Company";

   public Company(int empId, String empName) {
     this.empId = empId;
     this.employeeName = empName;
   }
 
   public static void changeCompanyName(String companyName) {
     CompanyName = companyName;
   }

   public void getEmployeeInfo() {
     System.out.println("Id : " + this.empId + ", Name : " + this.employeeName + ", Company Name : " + CompanyName);
   }

   public static void main(String arg[]) {
     Company c = new Company(2012, "Ashish");
     Company d = new Company(2013, "John");
     Company e = new Company(2013, "Vic");
 
     c.getEmployeeInfo();
     Company.changeCompanyName("Other Company"); // method accessed via Class Name.
     d.getEmployeeInfo();
     e.getEmployeeInfo();
   }
}


Look at the above example, we have created a separate method called “changeCompanyName()” which is public and static. That means, it can be accessed via class name. Also, this method is accessing the static instance variable and modifying the value of it. Note, when modified each object will have that modified value.

Static Initializer Block

If you want to initialize the value of static variable at run time. You can simply do this by using static instance initializer block. This block is always executed before the main method during class loading.

Example

class Company {
   private int empId;
   private String employeeName;
   private static String CompanyName;
 
   static {
     CompanyName = "Company";
     System.out.println("Executed before main, CompanyName : " + CompanyName);
   }

   public Company(int empId, String empName) {
     this.empId = empId;
     this.employeeName = empName;
   }
 
   public static void changeCompanyName(String companyName) {
     CompanyName = companyName;
   }

   public void getEmployeeInfo() {
     System.out.println("Id : " + this.empId + ", Name : " + this.employeeName + ", Company Name : " + CompanyName);
   }

   public static void main(String arg[]) {

     System.out.println("Main method started");
 
     Company c = new Company(2012, "Ashish");
     Company d = new Company(2013, "John");
     Company e = new Company(2013, "Vic");
 
     c.getEmployeeInfo();
     Company.changeCompanyName("Other Company");
     d.getEmployeeInfo();
     e.getEmployeeInfo();
   }
}

output :
Main method started
Executed before main, CompanyName : Company
Id : 2012, Name : Ashish, Company Name : Company
Id : 2013, Name : John, Company Name : Other Company
Id : 2013, Name : Vic, Company Name : Other Company

Leave a Reply

Your email address will not be published. Required fields are marked *