Does Java have an exponential operator?
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3
is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
There is the Math.pow(double a, double b)
method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b)
.
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9