The following code demonstrates an Example of Using Static Methods in Java.

In this program there is a class named Calculator. Basically, the Calculator class doesn’t have any instance members. Rather, it has two static methods that compute power of a number. While, the first method powerInt() computes an integer number raised to the power another integer. Similarly, the second method also computes the power. However, it takes two double values as its parameters.

The class CalculatorExercise2 is a public class that defines the main() method. As can be seen in the output, the two methods of the Calculator class are called using the class name. In order to call a static method, we don’t need the objects of that class. So, we use the class name to call static methods.

class Calculator
{
	public static int powerInt(int num1, int num2)
	{
		int p=1;
		for(int i=1;i<=num2;i++)
		{
			p*=num1;
		}
		return p;
	}
	public static double powerDouble(double num1, double num2)
	{
		return Math.pow(num1, num2);
	}
}
public class CalculatorExercise2
{
	public static void main(String[] args) {
	    int n1=3, n2=5;
	    double d1=2.2, d2=3.5;
	    System.out.println(n1+" raise to the power "+n2+" is "+Calculator.powerInt(n1, n2));
	    System.out.println(d1+" raise to the power "+d2+" is "+Calculator.powerDouble(d1, d2));	
	}
}

Output

Example of Using Static Methods in Java - Calculating the Power
Example of Using Static Methods in Java – Calculating the Power

Further Reading

Java Practice Exercise

programmingempire

Princites