Static Keyword in Java

Calling a method requires the involvement of an object. And we all are well aware of it too. But there is an interesting concept that lets us work the other way around. Static variables and static methods have a unique property that lets the programmers call a method without an object. So how does this take place? This article will answer that question.

Static Keyword in Java

Static is a reserved word in Java. We can apply this word with a variable, method, or even a class. The primary role of this keyword is to provide efficient memory management. The class contains the static keyword, not the object.
We can use the static keyword in the following ways:

  • Variable
  • Method
  • Block
  • Nested class

Java static variable:

Before learning about the static method, let us first understand how the static keyword is used with a variable.

  • Declaring any variable with the keyword static makes it a static variable.
  • Using this variable, we can refer to the property that every object in common possesses. This property should not be a unique attribute. Some examples are the name of the institution of students, the city name of the people, etc.
  • This variable makes use of the memory space only once during the loading of the class.

Pros of using Java static variable:

The primary advantage and the main role of using the static variable is that it saves a lot of memory space.

Without the static variable:

Here is a program snippet without the use of a static variable.

class Emp{
         int empid;
         String ename;
         String company = “FirstCode”;
 }

In case there are 200 employees in the company, each variable will be allocated to a separate memory space each time an object is created. Though the empid and ename would be different, the company would be the same. In this program, the common property is “company”. Declaring this variable as static will fetch the memory only once.

Program using a static variable:

class Employee{ 
   int empid;  
   String ename;  
   static String company ="FirstCode";//static variable  
  
//constructor  
   Student(int eid, String en){  
   empid = eid;  
   ename = en;  
   }  
   void display (){System.out.println(empid+" "+ename+" "+company);}  
}   
public class StaticVariable1{  
 public static void main(String args[]){  
 Employee e1 = new Employee(321,"Aaree");  
 Student s2 = new Employee(426,"Diya");    
 e1.display(); 
 e2.display(); 
 }  
}  

Output:

321 Aaree FirstCode
426 Diya FirstCode

Counter program without using static variable:

class CounterVar{ 
int count=0;//will get memory each time when the instance is created  
CounterVar(){  
count++;
System.out.println(count);  
}    
public static void main(String args[]){  
CounterVar v1=new CounterVar();  
CounterVar v2=new CounterVar();  
CounterVar v3=new CounterVar();  
}  
}  

Output:
1
1
1

Counter program using static variable:

The same program written above can also be modified using static variables.

class CounterVar2{ 
int count=0;//will get memory each time when the instance is created  
CounterVar()2{  
count++;
System.out.println(count);  
}    
public static void main(String args[]){  
CounterVar2 v1=new CounterVar2();  
CounterVar2 v2=new CounterVar2();  
CounterVar2 v3=new CounterVar2();  
}  
}  

Output:
1
2
3

Java static method:

Now, you might clearly know what a static keyword is and how it works with a variable. In this part of the article, let us discuss our main topic, “Static method in Java”.

You can make any method a static method just by adding the keyword static to it.

  • Static methods usually belong to a class rather than the object of a class.
  • There is no need to create an object to call a static method.
  • This method can access a static variable and modify it.

Features of Java static method:

  • We need not associate it with a class’s object.
  • It can only access static members.
  • Non-static members cannot be accessed using a static function.
  • Static members can be accessed directly when compared to a non-static method.
  • As a static method refers to a class, the syntax to call or refer to a static method is classname.methodname.

Difference between a static method and an instance method:

Let us now look at the common differences between an instance method and a static method.

Static Method Instance Method
The presence of objects is not vital. Objects are vital.
Can access only static attributes. All attributes are accessible.
Only the class name can access the method. Reverence of objects can be used to access the methods.
The static methods do not interact with the class or the instance methods. They function in an isolated manner.   We can modify the behaviour of the instance variables using an instance method.
These methods are bound to the class. Therefore, we access them using the class’s name.  These methods are bound to the class’s object. Therefore, we can access them using an object. 
Pass-by-reference programming comes under this category. Pass-by-value programming comes under this category.
They do not use self parameters. They only act as regular functions. Self parameters are used to access the class’s object.
Syntax: classname.methodName() Syntax: Objref.Methodname()

Declaration of Java static method:

We can declare the static method the same way as a normal one. The only difference is that we put the static keyword before the method name.

Example snippet for static method declaration:

class FirstCodeStatic
{
static void display()
{
System.out.println(“Learn Java with FirstCode”);
}
}

Calling the static method:

Calling the static method takes place by putting the class name in front of the method’s name.

Syntax:

ClassName.methodName()

Here, the ClassName is the name of the class, and following it is the static method’s name.

Sample program for a static method:

class Employee{ 
     int empid;  
     String ename;  
     static String company= "FirstCode";   
     static void modify(){  
     company = "FirstCodeTeam";  
     }  
    
Employee(int eid, String en){  
     empid = eid;  
     ename = en;  
     }  
     void display()
          {
         System.out.println(rollno+" "+name+" "+college);}  
         }    
public class StaticMethod{  
   public static void main(String args[]){  
   
Employee.modify();//calling modify method  
    //Object creation  
    Employee e1 = new Employee(134,"Riyaz");  
    Employee e2 = new Employee(254,"Kishore");
    Employee e3 = new Employee(332,"Hasi");   
   
e1.display();  
   
e2.display();  
   
e3.display();  
    }  
}  

Output:

134 Riyaz FirstCodeTeam
254 Kishore FirstCodeTeam
332 Hasi FirstCodeTeam

Sample program of a static method to calculate values:

class CalculateStaticMethod{  
 static int square(int s){  
  return s*s;  
  }   
  public static void main(String args[]){  
  int result=CalculateStaticMethod.square(3);  
 
System.out.println(result);  
  }  
}  

Output:

9

When to use Java Static method?

We cannot use the static method everywhere as we like. The role of this method is applicable only inside a class. Here are some common uses for a static method:

  • In cases where a method’s implication does not depend on the instance variables or the instance method, we can use the static method.
  • Static methods work well here when the instances do not alter a method’s code implementation.
  • A utility method can be introduced using static concepts for easily shareable properties.

Limitations in Java static method:

Static methods come with many restrictions that make them unique from normal methods.
We cannot invoke a class’s methods and instances using the static method. This is because objects are not required to access a static method. At the same time, we need an object to call the instance variables. The contrast in this causes an error.

class StaticRestriction{  
 int a=20; //non static variable
public static void main(String args[]){  
 System.out.println(a);  
 }  
}        

Output:

Compile Time Error

Difference between Static methods and static members in Java:

Property Static Method Static Members
Accessing We can access them using the class name. We can even access them using the class name.
Classmember The static methods are class members too. These methods bind to the class at the time of compilation.  The static methods are class members too. These members bind to the class at the time of compilation. 
Defaultvalue These methods do not consider the default values. There are many default static members. For example, the default value of a boolean member is false.
Overriding They don’t abide by the method overriding concept. They also don’t abide by the method overriding concept.

Java Static Block:

  • It initialises the static data member.
  • It executes before the main method during class loading.
class StaticBlock{ 
  static
{
System.out.println("Invoking Static block");
}  
  public static void main(String args[]){  
  
System.out.println("Inside Main Method");  
}  
}  

Output:

Invoking Static block
Inside Main Method

Common use for Java Static Methods:

Mainly, the static methods are used to call the static variables. These variables are accessed by the class name and a dot(.) followed by the method name. The method name comes after the keyword static.

Advantages of Java static methods:

  • Static methods are comparatively more efficient than non-static methods.
  • It can be accessed using the class name.
  • The creation of an object is not necessary.
  • The static keyword is used to manage the memory efficiently.
  • Static methods are globally accessible.

Static methods as Utility methods in Java:

The static methods act as utility methods in Collection, System, and Wrapper classes that are used due to higher efficiency. Therefore, the methods present in these classes are static and exhibit no effect on their behaviour. This is because the static methods depend only on their parameters.

Conclusion

I hope this article has cleared all your doubts regarding the static method concept in Java. The classification of differences between static methods, static variables, and instance methods would’ve made you picturise their uniqueness and importance. You are now ready to imply static methods in places where necessary.

Leave a Reply

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