Latest News: How to use Static Method in Java with Example - What is Static Method in Java with Example

How to use Static Method in Java with Example - What is Static Method in Java with Example

static methods in Java: 
we call them without creating an object of the class. 
Why is the main method static? Because program execution begins from it, and no object exists before calling it. Consider the example below:
 

class Languages {
  public static void main(String[] args) {
    display();
  }

  static void display() {
    System.out.println("Java is my favorite programming language.");
  }
}

Java static method vs instance method

Calling an instance method requires the creation of an object of its class, while a static method doesn't require it.

class Difference {

  public static void main(String[] args) {
    display();  //calling without object
    Difference t = new Difference();
    t.show();  //calling using object
  }

  static void display() {
    System.out.println("Programming is amazing.");
  }
 
  void show(){
    System.out.println("Java is awesome.");
  }
}

How to call a static method in Java?

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

import java.lang.Math;

class Another {
  public static void main(String[] args) {
    int result;
   
    result = Math.min(1020); //calling static method min by writing class name

    System.out.println(result);
    System.out.println(Math.max(100200));
  }
}


Popular Posts

MyMarket