![](./write-blog/images/591836965-16-pow-Method.png)
Harnessing the Power of the pow() Method in Java: An In-Depth Guide
Table of Content:
Description
This java tutorial shows how to use the pow(double a, double b)
method of Math class under java.lang package.
The method returns the value of the first argument raised to the power of the second argument.
Syntax
double pow(double base, double exponent)
Parameters
Here is the detail of parameters ?
-
base ? Any primitive data type.
-
exponenet ? Any primitive data type.
Return Value
-
This method returns the value of the first argument raised to the power of the second argument.
Example
public class MathPow { public static void main(String args[]) { double x = 10.635; double y = 9.76; System.out.printf("The value of e is %.4f%n", Math.E); System.out.printf("pow(%.3f, %.3f) is %.3f%n", x, y, Math.pow(x, y)); } }
Output
The value of e is 2.7183 pow(10.635, 9.760) is 10494407979.333 Press any key to continue . . .
Example
This java example source code demonstrates the use of pow(double a,double b)
method of Math class. Basically we just get the result of raising the base to the exponent
both comes from the user input.
import static java.lang.System.*; import java.util.Scanner; /* * This example source code demonstrates the use of * power(double a,double b) method of Math class * Get the result of raising the base number to exponent */ public class MathPower { public static Scanner scan; public static void main(String[] args) { // ask for user input out.print("Enter the base number:"); scan = new Scanner(System.in); // use scanner to get user console input, base double baseNumber = scan.nextDouble(); // use scanner to get user console input, exponent out.print("Enter the exponent:"); scan = new Scanner(System.in); double exponent = scan.nextDouble(); // get the result double result = Math.pow(baseNumber, exponent); out.println("Result = "+result); // close the scanner object to avoid memory leak scan.close(); } }
Output
Running the power(double a,double b)
method example source code of
Math class will give you the following output
Enter the base number:2 Enter the exponent:2 Result = 4.0 Press any key to continue . . .
Find power using Math.pow
/* Find power using Math.pow This java example shows how to find a power using pow method of Java Math class. */ public class FindPowerExample { public static void main(String[] args) { /* * To find a value raised to power of another value, use * static double pow(double d1, double d2) method of Java Math class. */ //returns 2 raised to 2, i.e. 4 System.out.println(Math.pow(2,2)); //returns -3 raised to 2, i.e. 9 System.out.println(Math.pow(-3,2)); } }
Output
4.0 9.0 Press any key to continue . . .