Java Program to Calculate the Power of a Number

In this program, you’ll learn to calculate the power of a number with and without using pow() function.

Example 1: Calculate power of a number using a while loop

1. `public class Power {`
2. ` public static void main(String[] args) {`
3. ` int base = 3, exponent = 4;`
4. ` long result = 1;`
5. ` while (exponent != 0)`
6. ` {`
7. ` result *= base;`
8. ` --exponent;`
9. ` }`
10. ` System.out.println("Answer = " + result);`
11. ` }`
12. `}`

When you run the program, the output will be:

`Answer = 81`

In this program, base and exponent are assigned values 3 and 4 respectively.

Using the while loop, we keep on multiplying result by base until exponent becomes zero.

In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81.

Example 2: Calculate power of a number using a for loop

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

When you run the program, the output will be:

`Answer = 81`

Here, instead of using a while loop, we’ve used a for loop.

After each iteration, exponent is decremented by 1, and result is multiplied by base exponent number of times.

Both programs above doesn’t work if you have a negative exponent. For that, you need to use pow() function in Java standard library.

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

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

When you run the program, the output will be:

`Answer = 0.012345679012345678`

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