You are here

Java static method

Java static method program: static methods in Java can be called without creating an object of the class. Why we write static keyword when defining main method? Because a program execution begins from main and no object has been created yet. Consider the example below to improve your understanding of static methods.

Java static method example program

  1. class Languages {
  2.   public static void main(String[] args) {
  3.     display();
  4.   }
  6.   static void display() {
  7.     System.out.println("Java is my favorite programming language.");
  8.   }
  9. }

Output of program:
Java static method program

Java static method vs instance method

Instance method requires an object of its class to be created before it can be called while static method doesn't require object creation.

  1. class Difference {
  3.   public static void main(String[] args) {
  4.     display();  //calling without object
  5.     Difference t = new Difference();
  6.;  //calling using object
  7.   }
  9.   static void display() {
  10.     System.out.println("Programming is amazing.");
  11.   }
  13.   void show(){
  14.     System.out.println("Java is awesome.");
  15.   }
  16. }

Output of program:
Static vs instance method program

Using static method of another classes

If you wish to call a static method of another class, then you have to write class name while calling the static method as shown in the example:

  1. import java.lang.Math;
  3. class Another {
  4.   public static void main(String[] args) {
  5.     int result;
  7.     result = Math.min(10, 20); //calling static method min by writing class name
  9.     System.out.println(result);
  10.     System.out.println(Math.max(100, 200));
  11.   }
  12. }

Output of program:

  1. 10
  2. 200

We are using min and max methods of Math class; min returns the minimum of two integers and max returns maximum of two integers. Following will produce an error:

  1. min();

We need to write class name because many classes may have a method with the same name which we are calling.