Calculate power of integer number in java (example)

  • Given a integer number, find out the power of given number.

Methods to calculate power of given number.

  • Calculate power of number using while loop method.
  • Find out power using JDK Math class
Method Name Description
double pow(double a, double b) Returns the value of the first argument raised to the power of the second argument.

Examples to find power of integer number in java

Example 1 : calculate power of input number : 4²

Enter base number : 4
Enter power number : 2

Power of number = 4² = 16

Example 2 :

Enter base number : 10
Enter power number : 3

Power of number = 10³ = 1000

Program: calculate power of integer using loop & JDK method

package org.learn;

import java.util.Scanner;

public class PowerOfNumber {

    private static int powerUsingLoop(int baseNumber, int power) {

        int outputNumber = 1;
        int index = 0;
        while (index < power) {
            outputNumber = baseNumber * outputNumber;
            index++;
        }

        return outputNumber;
    }

    private static int powerMathClass(int baseNumber, int power) {
        return (int) Math.pow(baseNumber, power);
    }

    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter base number : ");
            int baseNumber = scanner.nextInt();

            System.out.print("Enter power number : ");
            int power = scanner.nextInt();

            int powerResult = powerUsingLoop(baseNumber,power);

            System.out.println("Power of number using Loop :"
                                            +powerResult);

            powerResult = powerMathClass(baseNumber,power);

            System.out.println("Power of number using Math class :"
                                             +powerResult);
        }
    }
}

Output: calculate power of integer using loop & JDK method

Enter base number : 4
Enter power number : 2
Power of number using Loop :16
Power of number using Math class :16

************************************************
Enter base number : 10
Enter power number : 3
Power of number using Loop :1000
Power of number using Math class :1000
Scroll to Top