Home > Tutorial > Java Find Square Root Example

Java Find Square Root Example

If you need to find the square root of a number in your Java program, you can use the Math.sqrt() method that comes with Java. The method will return the correctly rounded positive square root of a double value. This method takes a double as the single argument and returns a double as the result.

There are a few special circumstances that may come up with using the sqrt() method.

  • If the argument is NaN or less than zero, then the result is NaN.
  • If the argument is positive infinity, then the result is positive infinity.
  • If the argument is positive zero or negative zero, then the result is the same as the argument.


Java Find Square Root Example Source Code

package com.jcd.java.tutorials;

public class JavaMathSquareRoot 
{

	public static void main(String[] args) 
	{
		
		System.out.println("Square root of 3: "+Math.sqrt(3));
		System.out.println("Square root of 6: "+Math.sqrt(6));
		System.out.println("Square root of 9: "+Math.sqrt(9));
		System.out.println("Square root of 12: "+Math.sqrt(12));
		System.out.println("Square root of 81: "+Math.sqrt(81));
		System.out.println("Square root of 100: "+Math.sqrt(100));
	}

}


Java Find Square Root Example Output

Square root of 3: 1.7320508075688772
Square root of 6: 2.449489742783178
Square root of 9: 3.0
Square root of 12: 3.4641016151377544
Square root of 81: 9.0
Square root of 100: 10.0


Smedley
Posted by

Smedley

Smedley has been programming in Java for about twenty years. He enjoys sharing code samples to other fellow Java coders.

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot