We are going to share a java program to calculate power of a number. If you are a Java beginner and want to start learning the Java programming, then keep your close attention in this tutorial as I am going to share how to write a java program to calculate power of a number.
Copy the below Java program and execute it with the help of Javac compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class JavaExample { public static void main(String[] args) { //Here number is the base and p is the exponent int number = 2, p = 5; long result = 1; //Copying the exponent value to the loop counter int i = p; for (;i != 0; --i) { result *= number; } //Displaying the output System.out.println(number+"^"+p+" = "+result); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class JavaExample { public static void main(String[] args) { int number = 5, p = 2; long result = 1; int i=p; while (i != 0) { result *= number; --i; } System.out.println(number+"^"+p+" = "+result); } } |
1 2 3 4 5 6 7 | public class JavaExample { public static void main(String[] args) { int number = 10, p = 3; double result = Math.pow(number, p); System.out.println(number+"^"+p+" = "+result); } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.