Java Program to Calculate Power of a Number

In this post, we will write java programs to calculate power of a number in following methods

Method 1:

public class JavaExample {
    public static void main(String[] args) {
    	//Here number is the base and p is the exponent
        int number = 5, p = 2;
        long result = 1;
        
        //Copying the exponent value to the loop counter
        int i = p;
        for (;i != 0; --i)
        {
            result *= number;
        }
        
        //Displaying the output
        System.out.println(number+"^"+p+" = "+result);
    }
}

 

Output

5^2 = 25

 

Method 2:  pow() function

public class JavaExample {
    public static void main(String[] args) {
    	int number = 10, p = 3;
        double result = Math.pow(number, p);
        System.out.println(number+"^"+p+" = "+result);
    }
}

 

Output

5^2 = 25