Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Math.pow()

Raises a number to a power.

Available since: Java 1.0

Syntax

static double pow(double a, double b)

Parameters

ParameterTypeDescription
adoubleThe base.
bdoubleThe exponent; can be fractional or negative.

Return value

doubleThe result as a double.

Examples

Powers, and a root through a fractional exponent:

void main() {
    IO.println(Math.pow(2, 10));
    IO.println(Math.pow(2, -1));
    IO.println(Math.pow(27, 1.0 / 3));
}

Output:

1024.0
0.5
3.0

The result is a double; an integer needs a cast:

void main() {
    int squares = (int) Math.pow(5, 2);
    IO.println(squares);
}

Output:

25

Notes

Java has no power operator: 2 ^ 10 is bitwise XOR, not exponentiation, and gives 8. For a square x * x is simpler. For large integer powers without precision loss use BigInteger.pow().

See also

  • Math.sqrt() — Returns the square root of a number.
  • Math.round() — Rounds a number to the nearest integer.
  • BigInteger — An integer of any size — for when even long is not enough.

In the tutorial

  • Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.

Thanks for reading!

Donate to the site — we work hard for you.