Java Math Raise Power Example

Use the Math.pow() method to raise a number to a power. When you raise a number by a power x, x is the number of times a number is multiplied. This method will return the value of the first argument raised to the power of the second argument.

Method Signature: double pow(double a, double b)

Note the following special circumstances that may come up with using the pow() method.

  • If the second argument is positive or negative zero, then the result is 1.0.
  • If the second argument is 1.0, then the result is the same as the first argument.
  • If the second argument is NaN, then the result is NaN.
  • If the first argument is NaN and the second argument is nonzero, then the result is NaN.
  • If the absolute value of the first argument equals 1 and the second argument is infinite, then the result is NaN.
  • If both arguments are integers, then the result is exactly equal to the mathematical result of raising the first argument to the power of the second argument if that result can in fact be represented exactly as a double value.


Java Math Raise Power Source Code

package com.jcd.java.tutorials;

public class JavaMathPow 
{

	public static void main(String[] args) 
	{
		
		//Raise 2 to the power of 2 (2 x 2)
		System.out.println("2 raised to 2nd power: "+Math.pow(2, 2));
		
		//Raise 2 to the power of 3 (2 x 2 x 2)
		System.out.println("2 raised to 3rd power: "+Math.pow(2, 3));
		
		//Raise 2 to the power of 4 (2 x 2 x 2 x 2)
		System.out.println("2 raised to 4th power: "+Math.pow(2, 4));
		
		//Raise 2.5 to the power of 2 (2.5 x 2.5)
		System.out.println("2.5 raised to 2nd power: "+Math.pow(2.5, 2));
		
		//Raise 2.5 to the power of 3 (2.5 x 2.5 x 2.5)
		System.out.println("2.5 raised to 3rd power: "+Math.pow(2.5, 3));
		
		//Raise 2 to the power of 4 (2.5 x 2.5 x 2.5 x 2.5)
		System.out.println("2.5 raised to 4th power: "+Math.pow(2.5, 4));

	}

}


Java Math Raise Power Output

2 raised to 2nd power: 4.0
2 raised to 3rd power: 8.0
2 raised to 4th power: 16.0
2.5 raised to 2nd power: 6.25
2.5 raised to 3rd power: 15.625
2.5 raised to 4th power: 39.0625


Add a Comment

Your email address will not be published. Required fields are marked *