Math.pow, exponents. In Java we may need to square or cube a number. With Math.pow we raise a number to any exponent. We use an exponentiation function.
public class Program {
public static void main(String[] args) {
// Raise 5 to the power of 2.// ... Then raise 3 to the power of 2.
double result1 = Math.pow(5, 2);
double result2 = Math.pow(3, 2);
// ... Display our results.
System.out.println(result1);
System.out.println(result2);
}
}25.0
9.0
Square. With methods we can add abstractions to our programs to make them easier to reason about. For example this program uses a square() method. It wraps a call to Math.pow.
Tip It may be easier to call square() than use Math.pow with specific arguments. The performance cost here is minimal or none.
public class Program {
static double square(int base) {
// We use Math.pow with a second argument of 2 to square.
return Math.pow(base, 2);
}
public static void main(String[] args) {
// Use square method.
double result1 = square(2);
double result2 = square(3);
double result3 = square(4);
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
}4.0
9.0
16.0
Review. With Math.pow we compute power functions. We square and cube numbers. With Math.pow we have a reliable and heavily-tested method in the Java framework to use.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.