How to Calculate Powers of Integers in Java


If you need to calculate the powers of Integers in Java, then you can do one of the following:

Option 1 – Using for loops

public class Power {
    public static void main(String args[]){
        int number = 5;
        int power = 3;
        int result = calculatePower(number,power);
        System.out.println(number+"^"+power+"="+result);
    }
    static int calculatePower(int num, int power){
        int answer = 1;
        if (num > 0 && power==0){
            return answer;
        } else if(num == 0 && power>=1){
            return 0;
        } else{
            for(int i = 1; i<= power; i++)
                answer = answer*num;
            return answer;
        }
    }
}

Option 2 – Using Recursion

public class Power {
    public static void main(String args[]){
        int number = 3;
        int power = 3;
        int result = CalculatePower(number,power);
        System.out.println(number+"^"+power+"="+result);
    }
    static int CalculatePower (int num, int pow){
        if (pow == 0)
            return 1;
        else
            return num * CalculatePower(num, pow - 1);
    }
}

Option 3 – Using Math.pow()

import java.lang.Math;
public class Power {
    public static void main(String args[]){
        int number = 6;
        int power = 3;
        double result = CalculatePower(number,power);
        System.out.println(number+"^"+power+"="+result);
    }
    static double CalculatePower (int num, int pow){
        return Math.pow(num,pow);
    }
}