Site icon TestingDocs.com

Java static methods

Overview

Java static methods do not require objects to be created. We can invoke a static method with the class name. These methods are also known as class methods.

We can use the static keyword to declare a method as a static method. For example, to declare a public static method

public static return_Type methodName( method_parameters ){

// method statements

}

 

Examples

Let’s see an example of static method.

public class StaticMethodsDemo {

	public static void main(String[] args) {
		System.out.println(exp(3,3));
	}

	//Static method to compute x^y
	private static double exp(double x,double y) {
		return Math.pow(x, y); // Math class static method
	}
}

 

 

All the methods in the code are static methods.

Math.pow() method is a static method . It returns the value of the first argument raised to the power of the second argument. Notice that we have invoked the static method with the class name. Math class is defined in the java.lang package. It is not necessary to import this class in the program. All the classes in the java.lang package are implicitly imported by the complier.

 

<ClassName>.<static_method>

Example

We cannot access or refer to non-static variables or call non-static methods in the static methods. We would encounter the following errors:

Cannot make a static reference to the non-static field

Cannot make a static reference to the non-static method

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

 

 

Exit mobile version