English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/)

Java Reader/Writer

Java other topics

Java program to calculate the power of a number

Comprehensive List of Java Examples

In this program, you will learn how to calculate the power of a number using and not using the pow() function.

Example1:Using while loop to calculate the power of a number

public class Power {
    public static void main(String[] args) {
        int base = 3, exponent = 4;
        long result = 1;
        while (exponent != 0)
        {
            result *= base;
            --exponent;
        }
        System.out.println("Answer = "); + result);
    }
}

When the program is run, the output is:

Answer = 81

In this program, values are assigned to base and exponent separately3and4。

Using while loop, we will multiply result by base until the exponent (exponent) becomes zero.

In this case, we multiply result by the base a total of4times, so result= 1 * 3 * 3 * 3 * 3 = 81。

Example2:Using for loop to calculate the power of a number

public class Power {
    public static void main(String[] args) {
        int base = 3, exponent = 4;
        long result = 1;
        for (; exponent != 0;) --exponent)
        {
            result *= base;
        }
        System.out.println("Answer = "); + result);
    }
}

When the program is run, the output is:

Answer = 81

Here, we use a for loop instead of a while loop.

The exponent is reduced after each iteration.1, and then result is multiplied by base, exponent times.

If your exponent is negative, the above two programs are invalid. For this, you need to use the pow() function from the Java standard library.

Example3: Calculate the power of a number using the pow() function

public class Power {
    public static void main(String[] args) {
        int base = 3, exponent = -4;
        double result = Math.pow(base, exponent);
        System.out.println("Answer = "); + result);
    }
}

When the program is run, the output is:

Answer = 0.012345679012345678

In this program, we use the Java Math.pow() function to calculate the power of a given base.

Comprehensive List of Java Examples