# Java program to calculate Power (x,n) using Recursion | Pow(x,n) with Example

The below logic will calculate the integer power of a number that is X^N where N is a integer. X ^ N is evaluated as X*X*X*….X up to N times that is X is multiplied by N times. This can be calculated by recursion, as recursion is a powerful mechanism which simplifies the logic too.

The algorithm for Power(double x, int n) will be as follows.

If n=0 , then the result is 1.0.

If n=1, then the result is the same as x.

If n>1, then the result is calculated by multiplying x by n times which can be calculated by recursion (x*Power(x,n-1))

if n<1, then n will be negative, that is x^-n which is equal to 1/x^n which can also be calculated by recursion (1.0 / Power(x, -n)); */

package net.javaonline; class Power { public static void main(String args[]) { if (args.length!=1) { System.out.println(&quot;Input Error, Syntax : java Power &quot;x^n&quot; &quot;); System.exit(0); } String strInput=args[0]; int pos=strInput.indexOf('^' , 0); double x=0; int n=0; //to split the x and n from the input string try { x=Double.parseDouble(strInput.substring(0,pos)); n=Integer.parseInt(strInput.substring(pos+1)); } catch (Exception e) { System.out.println(&quot;Error, Syntax : java Power &quot;x^n&quot; where n is integer&quot;); System.exit(0); } System.out.println(); System.out.println(x+&quot;^&quot;+n+ &quot; = &quot;+ pow(x,n)); } // Calculates the x raise to the power n static double pow(double x, int n) { if (n==0 || n==1) return (n==0?1.0 : x); else if (n&gt;1) return (x*pow(x,n-1)); else return (1.0/pow(x,-n)); } }

**Output**

Try with Live Demo