Static method in Java with example

Created with Sketch.

 

Static method in Java with example

Java static methods: 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:

Static method Java program

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

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

Output of program:
Java static method program

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.”);
}
}

Output of program:
Static vs instance method program

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(10, 20); //calling static method min by writing class name

System.out.println(result);
System.out.println(Math.max(100, 200));
}
}

Output of program:

10
200

We are using min and max methods of Math class; min returns the minimum of two integers, and max returns the maximum of two integers. Following results in error:

min();

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

Leave a Reply

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