How do you do exponents in Java?

Example 1: Calculate power of a number using a while loop

class Main {
  public static void main(String[] args) {

    int base = 3, exponent = 4;

    long result = 1;

    while (exponent != 0) {
      result *= base;
      --exponent;
    }

    System.out.println("Answer = " + result);
  }
}

Output

Answer = 81

In this program, base and exponent are assigned values 3 and 4 respectively.

Using the while loop, we keep on multiplying the result by base until the exponent becomes zero.

In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81.


Example 2: Calculate the power of a number using a for loop

class Main {
  public static void main(String[] args) {

    int base = 3, exponent = 4;

    long result = 1;

    for (; exponent != 0; --exponent) {
      result *= base;
    }

    System.out.println("Answer = " + result);
  }
}

Output

Answer = 81

Here, instead of using a while loop, we've used a for loop.

After each iteration, the exponent is decremented by 1, and the result is multiplied by the base exponent number of times.

Both programs above do not work if you have a negative exponent. For that, you need to use the pow() function in Java standard library.

In Java, we don’t have any direct operator for finding exponents. The most convenient way to calculate the exponent in Java is by using

5 rasise to 3 = 125
2 function.

In this Java tutorial, you will learn two different ways to calculate exponents in Java with code examples.

  1. Without using Maths.pow() / using for-loop
  2. Using Maths.pow()

1. Calculate exponent using Java for-loop

Basics are the building block for any programming language. So, we can simply use a for-loop and make our own logic in Java. Below is a Java program to do exponent of a number without Math.pow().


public class CalculateExponent1 {

	public static void main(String[] args) {
	//calculating exponent using for loop
	int base=5;
	int power=3;
	int result=1;
        if(power!=0){
           for(int i=1;i<=power;i++)
           {
            result*=base;
           }
         }
        System.out.println(base + " raise to " + power + " = " + result); 
	}
}

Output

5 rasise to 3 = 125

2. Java Math.pow() method to do exponents in Java

Java provides an inbuilt method to directly do exponents i.e

5 rasise to 3 = 125
2. The method simply accepts two parameters. Most importantly the two parameters must be of double type.

How do you do exponents in Java?

exponents in java Math.pow() method

Therefore, it is the most straightforward way of finding exponents in java.
The method returns the first parameter raised to the second parameter.

In addition, there are certain cases that programmers should know while using Math.pow() Java function.

The easiest way is to use Math library.

Use Math.pow(a, b) and the result will be a^b

If you want to do it yourself, you have to use for-loop

// Works only for b >= 1
public static double myPow(double a, int b){
    double res =1;
    for (int i = 0; i < b; i++) {
        res *= a;
    }
    return res;
}

Using:

double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);

The java.lang.Math.pow() is used to calculate a number raise to the power of some other number. This function accepts two parameters and returns the value of first parameter raised to the second parameter. There are some special cases as listed below:

Unfortunately, like some other widely used computer languages, Java does not come with an exponent operator, which means you have to do exponents through another method. Alternatively, in Java, the common math operations can be suitably titled Java .util.Math in the math static class.

This will support the following operation: common trigonometry, absolute value, exponents, and rounding. It is most common for the mathematical operations results to be “double” data-types, which can be cast down to floats and integers if required. As well as you can take help from any offshore JavaScript development to get this task done. But if you already decided to DIY, then….

Following are the steps for doing exponent in Java:

Step 1

Start with opening the Java editor you prefer, such as the Netbeans Integrated Development Environment, or the IDE.

Step 2

The create a new source file by selecting “File” and “New Class” or open an existing Java source file.

Step 3

At the very top of the document, for Java exponent type the following line:

import java.util.Math;

Step 4

Then, anywhere in the document, input the following formula to find the exponent Java:

double result = Math.pow(number, exponent);

Swap “number” with the base value and the value of the “exponent.” 

For example:

double result = Math.pow(10,5);

You will get the result: 100,000, or 10^5.

Additionally, there are some special considerations to be mindful of when to Pow () method is used for exponent in Java; they are as follows:

  • In case the second value is zero, whether positive or negative, the result will be 1.0.
  • In case the second value is one, then the resulting value would be the same as the first number.
  • In case the second value is N, then the output will also be N.

For Loop Method

If the number you are raising is 1 or greater, you can also try the loop method. Although the technique is lengthy, thankfully, you can skip some work using the existing code provided below to copy and paste directly to Java IDE to skip writing the code entirely by yourself.

You can use the code given below by replacing the numbers with your own values that you need to calculate and then run the code:

package exponent_example;

public class Exponent_example {

public static void main(String[] args) {

double num = 2;

int exp = 3;

double answer = Pow(num, exp);

System.out.println(answer);

}

public static double Pow(double num, int exp){

double result =1;

for (int i = 0; i < exp; i++) {

result *= num;

}

return result;

}}

Replace ‘num = 2’ with the base number and ‘exp = 3’ with the power. It is important that the exponent value is an integer, which is denoted by the “int.” The necessity of the integer is one of the limitations of this method. 

Read Also

  • WordPress Security Guide
  • Guide To Convert a HTML to PDF in C#
  • How to Build Your First Profitable eCommerce Website
  • 7 Must-Have WooCommerce Plugins
  • WooCommerce Shortcodes Guide
  • How to Change a File Extension in Windows
  • Signs your Business Needs Custom Software Development

How to Watch Harry Potter on Netflix

How to Watch Netflix With NordVPN

How to Install Android Apps on Windows 11

How To Change Your Username On Reddit

Markhascole

Mark is a cyber security enthusiast. He loves to spread knowledge about cybersecurity with his peers. He also loves to travel and writing his travel diaries.

How do you put exponents in Java?

The Java Math exp() method returns the Euler's number e raised to the power of the specified value. That is, Math. exp(4.0) = e4.0 . Here, exp() is a static method.

How do you type to the power of 2 in Java?

The power function in Java is Math. pow(). It is used to get the power of the first argument to the second argument..
public class PowerFunc1 {.
public static void main(String[] args).
double a = 5;.
double b = 2;.
System. out. println(Math. pow(a, b)); // return a^b i.e. 5^2..

How do you write 10 to the power 9 in Java?

Since 109 fits into an int and is also exactly representable as a double , you can do this: int exp = (int) Math. pow(10, 9); BigInteger answer = BigInteger.

How do you use powers of 10 in Java?

Math. pow(10, exponent)