Power of Number in Java
Raise an integer to a power in Java by multiplying a long accumulator once per loop pass. An exponent of zero returns 1; negative exponents need other logic.
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter base: ");7 int a = sc.nextInt();8 System.out.print("Enter exponent: ");9 int b = sc.nextInt();1011 long result = 1;12 for (int i = 1; i <= b; i++) {13 result *= a;14 }1516 System.out.println(a + " ^ " + b + " = " + result);17 sc.close();18 }19}
Sample Output
Enter base: 3 Enter exponent: 4 3 ^ 4 = 81
The product changes 1 → 3 → 9 → 27 → 81 in four passes. The displayed ^ is just a label.
In this one
- Trace a repeated product
- Separate printed symbols from operators
- Recognise unsupported negative powers
How it works
- 1
Read base a and exponent b.
- 2
Set result to 1.
- 3
Multiply by a for each i from 1 to b.
- 4
Print the base, exponent, and final result.
Edge cases
Exponent zero
Enter 3 and 0
No pass runs and the result is 1.
Long result limit
Use a large base or exponent
long can still overflow. Keep small inputs or use a larger-number approach when needed.
What's going on
Raise a whole-number base to a non-negative power using a loop. For 3 to power 4, multiply four copies of 3. This example focuses on the changing product so you can see the work hidden inside a built-in power function.
Scanner is the keyboard reader. result starts at 1 and is multiplied by a once per pass from i = 1 to b. The long type gives more space for whole-number results than int, but it still has a limit. The final message places a ^ b between labels to show the mathematical idea.
The ^ inside that printed text is only a symbol in a message. In Java calculations, ^ is exclusive OR, an operation that compares binary bits, not exponentiation. Do not replace the loop with a ^ b. Negative exponents need fractional answers and are outside this version; b = 0 leaves result at 1.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is 3 to the fourth power?
Pick an answer to check it.
Question 2
Is Java ^ the power operator?
Pick an answer to check it.
Questions people ask
Is ^ performing the power in the output line?
No. It is inside a string and is printed as text.
What happens for a negative exponent?
This loop is skipped and prints 1, which is not the intended mathematical answer. Reject negative b for this exercise.
How is this different from multiplying a by b?
a * b adds a copies of b conceptually; a power multiplies b copies of a together.