Static Methods and Variables in Java

static variablesstatic constants

In the previous blog, we learned to define our own class, constructors, implicit and explicit parameters, etc. If you want to know more about it, visit Defining Own Classes in Java. In all our codes we have seen the main() method with the static keyword. In this blog, we will understand why we use the static keyword for methods and variables.

Static Variables

When we define static variables in our code, then please make a note that there is only one static variable per class. On the contrary, each object has its own copy of non-static instance variables. For example :

e.g.

class AtrowelStudent {
  private static int staticId = 1;
  private int id;
}

In the above example, we have define static field i.e. staticId and non-static field i.e. id. Each object of the class AtrowelStudent will have its own copy of id and will only have one copy of staticId which will be shared by all the instances of the class i.e. AtrowelStudent. For example, if we defined 100 objects of class AtrowelStudent, then there will be 100 instance fields i.e. id for each object, but there will be only one static field i.e. staticId per class. The static field staticId will be present even if there are no objects for AtrowelStudent class. Because the static field i.e. staticId belongs to the class and not to the object of the class.

e.g.

public void setAtrowelId(){
  id = staticId;
  System.out.println("The value of id:"+ id);
  staticId++;
  System.out.println("The value of static id:"+ staticId);
}

In the above example, the instance field i.e. id will be set to the value of the static field i.e. staticId, and the static field i.e. staticId will be incremented.


Static Constants

Static Variables are not used very frequently(used rarely), but static constants are used most frequently. For example, if we consider the Math class then we will find almost all constants static. For example PI(Pie), E(Exponent), pow(power), etc. All these constants will be accessible by the class name i.e. Math.

e.g.

Math.PI
Math.E
Math.pow

In the above example, suppose there would be no static keyword, then all these fields would be instance fields of Math class and would use an object of Math class to access the fields. Each object of the Math class would have its own copy of the fields like PI, E, po, etc.


Methods with Static Keyword(static methods)

Methods declared as static doesn’t require an object to perform its operation. For example, the sqrt() method of the Math class is a static method.

Math.sqrt(double atrowelValue);

The above expression returns the square root of the given number. sqrt() method doesn’t require a Math object for performing its operation. Static methods don't use this parameter because it doesn't have implicit parameters. If you want to learn more about implicit parameters then we can go and visit the previous blog. If we take the above example from the Static Variables topic, then the static method i.e. staticId of class AtrowelStudent cannot access the non-static field i.e. id, because it does not require an object to perform its operation. In contrast, static methods can access the static fields. For example,

e.g.

public static void getStaticId() {
  System.out.println("The value of static field is:" +  staticId);
}

We can call getStaticId() method using the following:

AtrowelStudent.getAtrowelStaticId();

You may be having a question: Can we eliminate the static keyword for getStaticId? Yes, we can eliminate the static keyword and can use the above method, but then we will require an object of type AtrowelStudent class for calling the method.

It is preferred to use the static methods in the following situations:

  1. When there is no need for a method to access the object because all the parameters required are defined explicitly

    e.g.

    Math.sqrt();
  2. When the method wants to access only the static fields of the class

    e.g.

    AtrowelStudent.getAtrowelStaticId();

Difference between the static methods

C++JAVA
C++ uses scope resolution operator(::) to access the static fields or methods e.g. Math::PIJava doesn’t require a scope resolution operator(::) to access static fields or methods. It can be simply accessible by dot(.) operator. e.g. Math.PI

Factory Method

In general, a factory is the place where we create the product. The same is the concept with the factory method, factory method defines an interface and allows the subclass to decide which objects to be created. LocalDate and NumberFormat class uses the static method in order to create an object. We have already learned about the LocalDate class in the previous blog. Here we will learn about the NumberFormat class.

e.g.

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
NumberFormat percentFormatter = NumberFormat.getPercentInstance();
double x = 0.1;
System.out.println(currencyFormatter.format(x));
System.out.println(percentFormatter.format(x));

Looking at the code you may be having a question: why did the NumberFormat class not use the constructor rather than using the factory method? There are two reasons for this:

  1. We cannot provide(give) any name to the constructor. We have seen in our previous blog that the constructor has the same name as the class. But as you can see in the above example we need two different names in order to get the currency instance and percent instance.
  2. If we use the constructor, then we cannot vary the object that is created(constructed). Factory method returns the object of the class decimalformat which is the child class(subclass) that is derived(inherited) from the NumberFormat.

main() Method

As we have learned earlier, static methods are the only methods that don’t require an object for performing their operations. e.g Math class never requires its object to create, in order to call any of its methods e.g. Math.sqrt. For a similar reason, the main() method is static.

e.g.

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

main() method does not require an object for its operation. In fact when the program starts, there is no object present. As we are familiar with the fact that the main() method is the method from which the execution of the code starts. main() method should be static so that Java Virtual Machine(JVM) can easily load the class into the memory and call the main() method. If the main() method wouldn’t be static then JVM would not be able to call it because it would require any object so the method would be called using that object, but as there is no object present it would be difficult for JVM to call it.

e.g.

public class MainMethodEx {
  public static void main(String[] args) {
      var student = new AtrowelStudent[4];
      student[0] = new AtrowelStudent("John", 30000);
      student[1] = new AtrowelStudent("Sam", 640000);
      student[2] = new AtrowelStudent("Tom", 69000);
      student[3] = new AtrowelStudent("Smith", 61000);

      for (AtrowelStudent atrowelValue : student) {
          atrowelValue.setAtrowelId();
          System.out.println("Name=" + atrowelValue.getName() + ",Id=" + atrowelValue.getAtrowelId() + ",Salary="
          + atrowelValue.getSalary());
      }

      int atrowelNo = AtrowelStudent.getAtrowelStaticId();
      System.out.println("Next id=" + atrowelNo);
  }
}

class AtrowelStudent {
  private static int atrowelStaticId = 1;
  private String aName;
  private double aSalary;
  private int atrowelId;

  public AtrowelStudent(String atrowelName, double atrowelSalary) {
      aName = atrowelName;
      aSalary = atrowelSalary;
      atrowelId = 0;
  }

  public String getName() {
      return aName;
  }

  public double getSalary() {
      return aSalary;
  }

  public int getAtrowelId() {
      return atrowelId;
  }

  public void setAtrowelId() {
      atrowelId = atrowelStaticId;
      atrowelStaticId++;
  }

  public static int getAtrowelStaticId() {
      return atrowelStaticId;
  }
}

Output

Name=John,Id=1,Salary=30000.0
Name=Sam,Id=2,Salary=640000.0
Name=Tom,Id=3,Salary=69000.0
Name=Smith,Id=4,Salary=61000.0
Next id=5

Core Java Tutorial

Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.