In this example you will learn about how to calculate power in java.

Java POWER Calculation

In this example you will learn about how to calculate power in java.

In Mathematics calculating power is means multiply a number, called 'base' number of times by another number, called exponent i.e. if there are two numbers 'X' and Y then it is denoted as XY or read as Y is raised to the power of X.

Example :

Power.java

```import java.util.Scanner;

public class Power
{
static double power;
public static double pow(double bs, double pw)
{
if((bs>0.0 && pw==0.0) || bs<0.0 && pw==0.0)
return 1;
else if(bs>0.0 && pw>0.0)
{
power = bs*pow(bs,pw-1);
return power;
}
else if(bs>0.0 && pw<0.0)
{
power = 1/bs*pow(bs, pw+1);
return power;
}
else if(bs<0.0 && pw>0.0)
{
power = (bs)*pow(bs,pw-1);
return power;
}
else
{
power = 1/bs*pow(bs, pw+1);
return power;
}
}
public static void main(String args[])
{
double pw;
Power p = new Power();
Scanner scan = new Scanner(System.in);
System.out.println("Enter base number");
double a = scan.nextDouble();
System.out.println("Enter the exponent number");
double b = scan.nextDouble();
pw = p.pow(a, b);
System.out.println(pw);
}
}```

Output :

Go to Topic «PreviousHomeNext»