by Dinesh Thakur

It is possible to have static methods in a class in the same way as we have static fields. The static method is similar to instance method) of a class but the only difference is that the static method can be called through its class name without creating any object of that class. A static method is also called class method as it is associated with a class and not with individual instance of the class. We have already seen the sqrt () method which is a static method within Java standard Math class. A method is declared static when its behavior is not dependent on the instance variable just like Math.sqrt (4.5).This method never uses instance variables so it does not need to know about the specific object.

There is an important restriction on the static method that it can access only static fields and other static methods of a class. This is because static methods can exist and be used even if no objects of that class have been created. If an attempt is made to access a non-static field from the static method then the compiler will generate an error as the static method does not know which nonstatic field value to use. Similarly, a static method cannot access non-static method either because non-static methods are usually associated with instance variable state.

// Program That Maintain Bank Account Information about Various Customers

class Account
      int accountNo; //account ID
      double balance ;
      static double rate = 0.05;
      void setData(int n,double bai)
         accountNo = n ;
         balance = bai ;
      void quarterRatecal()
         double interest = balance * rate * 0.25 ;
         balance += interest ;  
      static void modifyRate(double incr)
         rate += incr;
         System.out.println("Modified Rate of Interest : " + rate);
      void show()
         System.out.println("Account Number : " + accountNo);
         System.out.println("Rate of Interest : " +rate);
         System.out.println("Balance : "+ balance);
  public class StaticMethod
      public static void main(String[] args)
        Account acc1 = new Account();
        Account acc2 = new Account();
        System.out.println("Customel Information......");
        acc1.quarterRatecal();  //Calculate interest; //display account interest
        System.out.println("Customer2 Information......");
        acc2.quarterRatecal(); //Calcuate interest; //display account information

Static Methods in Java Examples

The Account class contains a static method modifyRate ().It modifies the rate of interest by the value specified as argument (0.01). The method modifyRate () is made static in the class as we are only using static field rate in it. Only static method can access a static field.