Java Program to Find Power of a Number

Calculating the power of a number is a common mathematical operation in programming. In Java, it helps beginners understand loops, multiplication, and mathematical logic.

In this tutorial, we will create a Java program to compute the value of a number raised to a given exponent.

By the end of this guide, you will understand how repeated multiplication works in Java.

Concept Overview

The power of a number is calculated as base^exponent. For example, 2^3 = 2 × 2 × 2 = 8.

We use a loop to multiply the base repeatedly exponent number of times.

Program

Java
import java.util.Scanner;

public class PowerOfNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter base: ");
        int base = sc.nextInt();

        System.out.print("Enter exponent: ");
        int exponent = sc.nextInt();

        long result = 1;

        for (int i = 1; i <= exponent; i++) {
            result *= base;
        }

        System.out.println(base + " raised to power " + exponent + " is: " + result);
    }
}

Output

TEXT
Enter base: 2
Enter exponent: 3
2 raised to power 3 is: 8

Detailed Explanation

The program starts by taking input for base and exponent using the Scanner class.

A result variable is initialized to 1 because multiplication starts from 1.

A loop runs exponent times, multiplying the result by the base each time.

Finally, the computed power value is displayed.

Example Walkthrough

Let us consider base = 2 and exponent = 3.

Step-by-step calculation: 1 → 2 → 4 → 8.

The final output is 8.

Applications

Power calculations are used in scientific computations, financial models, and algorithm design.

Advantages of This Approach

This program helps beginners understand loops and repeated multiplication.

It builds a foundation for mathematical programming.

Limitations

The program does not handle negative exponents.

Improvements You Can Make

You can improve this program using Math.pow() for more efficiency.

You can also handle negative exponents and floating-point values.

This Java program strengthens understanding of loops and mathematical computations.