In the previous article, we have seen Java Program to Convert a Float Value to Absolute Value

In this article we are going to see how to find power of a number using java programming language.

## Java Program to Calculate Power of a Number

Power of a number represents multiplying the number with itself for a certain number of times. During calculation of power we have two important terms i.e.

**Base:**Number it self which represents what number is to be multiplied.**Exponent:**Number which tells number of times the base number is to be multiplied.

**Example:**

6^{5} = 7,776

Let’s see different ways to find power of a number.

### Method-1: Java Program to Calculate Power of a Number By Using For Loop

As we got an idea that power is the multiplication of base with itself based on exponent value(number of times). So we can take a for loop and multiplying the number with itself based on exponent value.

**Approach:**

- Create scanner class object.
- Take user input for base and exponent.
- Initialize result with 1.
- Run a for loop from
`i = 0`

to`exponent`

value. - Inside the loop multiply result with the base until the loop exhausts.

**Program**:

import java.util.Scanner; public class Main { public static void main(String[] args) { //Scanner class object created Scanner sc = new Scanner(System.in); //Taking user input of base value System.out.println("Enter the base number: "); double base = sc.nextDouble(); //TAking user of exponent value System.out.println("Enter the exponent: "); double exponent = sc.nextDouble(); //double variable 'result' declared to hold power value double result = 1; //finding power by using for loop for (int i = 0; i < exponent; i++) { result *= base; } System.out.println("The result is: " + result); } }

Output: Enter the base number: 2 Enter the exponent: 3 The result is: 8.0

### Method-2: Java Program to Calculate Power of a Number By Using Pow() Function

In Java we have inbuilt `Math.pow()`

function which can be used to find power of a number.

Syntax: `Math.pow(base,exponent)`

**Approach:**

- Create scanner class object.
- Take user input for base and exponent.
- By using
`Math.pow()`

function find the power.

**Program:**

import java.util.Scanner; public class Main { public static void main(String[] args) { //Scanner class object created Scanner sc = new Scanner(System.in); //Taking user input of base value System.out.println("Enter the base number: "); double base = sc.nextDouble(); //TAking user of exponent value System.out.println("Enter the exponent: "); double exponent = sc.nextDouble(); //find power by using pow() function double result = Math.pow(base, exponent); System.out.println("The result is: " + result); } }

Output: Enter the base number: 3 Enter the exponent: 3 The result is: 27.0

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

**Related Java Programs:**