To find the power of a number in Java, you can use the Math.pow()
method from the java.lang.Math
class.
The Math.pow()
method takes two arguments: the base and the exponent. It returns the result of raising the base to the power of the exponent.
Here's an example of how to find the power of a number in Java:
double base = 2; double exponent = 3; double result = Math.pow(base, exponent); System.out.println("The result is " + result);
In the above example, the base is 2 and the exponent is 3. The Math.pow()
method is called with these arguments and the result (8) is stored in the result
variable. The result
variable is then printed to the console.
Keep in mind that the Math.pow()
method returns a double
value, so you will need to use a double
data type to store the result. If you need to find the power of an integer, you can cast the result to an int
data type if necessary.
For example:
int base = 2; int exponent = 3; int result = (int) Math.pow(base, exponent); System.out.println("The result is " + result);
In this example, the result of the Math.pow()
method is cast to an int
data type before it is stored in the result
variable. The result
variable is then printed to the console.