Learn static method in java with example i.e. how to write static method in a class and why do we use static methods in application.

STATIC METHOD

Before explanation, see how we make a method static in a class.

It’s simple, just write static keyword before the method.

class Utility {
	
	//static method
	public static void Scan(){
		System.out.println("static method in java");
	}
}

“Call Static methods of a class using class name without creating object”

We can call static methods of a class using only class name. We don’t need to create an object of the class in java program and then call the static method.

Note that if method is not static, then you must create an object of the class then call the method. This is not the case with static method.

Below java code example, demonstrate calling static method without creating an object of the class.

Static Method Code Example

class Utility {

	// static method
	public static void Scan() {
		System.out.println("static method in java");
	}
}

public class Sample {

	public static void main(String[] args) {

		Utility.Scan();

	}
}

Output:
static method in java

“Use static method if you don’t need to create an object of the class.”

Here is one of the examples you can see, where static method is mandatory.

Notice that the main () method, the starting point of the java programs is static. So, the JVM can call the main () without creating an object of the class Sample.

public class Sample {

	public static void main(String[] args) {
		
		System.out.println("Hello World");

	}
}

Related Posts