Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find x to the power y (xy).

Java Code Example — Basic Programs

ADVERTISEMENT

Java Program to find x to the power y (xy).

Objective

Write a Java program to find the value of a number raised to the power of another.

Algorithm / Approach

  1. Prompt the user to enter a base and an exponent.
  2. Use Math.pow(x, y) to calculate the power.
  3. Cast the resulting double into an int if a whole number is desired.
  4. Print the result.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Base: ");
  int x = s.nextInt();
  System.out.print("Enter Power: ");
  int y = s.nextInt();
  int r =(int) Math.pow(x,y);
  System.out.println("Result = "+r);
 }
}

Expected Output

Enter Base: 5
Enter Power: 3
Result = 125

Explanation of the Program

  • The base x and exponent y are taken as input.
  • The Math.pow(x, y) method computes x raised to the power of y.
  • Because Math.pow() returns a double, it is explicitly cast to an int before being stored in r.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Forgetting to cast Math.pow() to an int when integer output is needed.
  • Swapping the base and the exponent arguments.
ADVERTISEMENT