How to Use Math.pow in Java: Simple Guide with Examples
In Java, use
Math.pow(base, exponent) to calculate the power of a number, where base and exponent are double values. It returns a double representing base raised to the power of exponent. For example, Math.pow(2, 3) returns 8.0.Syntax
The Math.pow method takes two arguments: base and exponent, both as double values. It returns a double value which is the result of raising the base to the power of the exponent.
base: the number to be raisedexponent: the power to raise the base to
java
double result = Math.pow(base, exponent);
Example
This example shows how to use Math.pow to calculate powers of numbers and print the results.
java
public class PowerExample { public static void main(String[] args) { double base = 2; double exponent = 3; double result = Math.pow(base, exponent); System.out.println(base + " raised to the power of " + exponent + " is " + result); // Another example System.out.println("5^4 = " + Math.pow(5, 4)); } }
Output
2.0 raised to the power of 3.0 is 8.0
5^4 = 625.0
Common Pitfalls
Common mistakes when using Math.pow include:
- Using integer types without casting, which can cause unexpected results or require explicit casting.
- Expecting an integer return type;
Math.powalways returns adouble. - Using negative bases with fractional exponents, which can result in
NaN(not a number).
java
public class PitfallExample { public static void main(String[] args) { // Wrong: expecting int result int wrongResult = (int) Math.pow(2, 3); // Needs casting System.out.println("Casted result: " + wrongResult); // Problematic: negative base with fractional exponent double nanResult = Math.pow(-2, 0.5); System.out.println("Result of Math.pow(-2, 0.5): " + nanResult); } }
Output
Casted result: 8
Result of Math.pow(-2, 0.5): NaN
Quick Reference
| Usage | Description |
|---|---|
| Math.pow(base, exponent) | Returns base raised to the power exponent as a double |
| base and exponent | Both should be double values for accurate results |
| Return type | Always double, cast if integer needed |
| Negative base with fractional exponent | May return NaN (not a number) |
Key Takeaways
Use Math.pow(base, exponent) to calculate powers, both as double values.
Math.pow always returns a double, so cast if you need an integer result.
Avoid negative bases with fractional exponents to prevent NaN results.
Remember to import java.lang.Math implicitly; no extra import needed.
Math.pow is useful for any power calculation in Java, from squares to complex exponents.