Languages
[Edit]
EN

Java - Math.sqrt() method example

0 points
Created by:
Lia-Perez
565

Math sqrt is a static method that returns a number which is the square root of input value. The method works only on positive real numbers.

public class MathExample {

    public static void main(String[] args) {
        System.out.println( Math.sqrt(  4   ) ); //  2.0
        System.out.println( Math.sqrt(  9   ) ); //  3.0

        System.out.println( Math.sqrt(  2   ) ); //  1.4142135623730951
        System.out.println( Math.sqrt(  0.5 ) ); //  0.7071067811865476
        System.out.println( Math.sqrt(  0   ) ); //  0.0
        System.out.println( Math.sqrt( -1   ) ); //  NaN
    }
}

1. Documentation

Syntax
package java.lang;

public final class Math {

    public static double sqrt(double number) { ... }

}

Note: Classes in the java.lang package are imported automatically, so it is not necessary to do it manually - we use just Math.sqrt() call.

Parametersnumber - double value in the range 0 to +Infinity (primitive value).
Result

Square root number value in range 0 to +Infinity (primitive value).

If the operation can not be executed NaN is returned.

Descriptionsqrt is a static method that returns a number which is square root of input value. The method works only on positive real numbers.

2. Square root with Math.pow method examples

In this example, the way how to calculate square root using power function is presented. 

public class MathExample {
    
    static double calculateSqrt(double value) {
        return Math.pow(value, 0.5);
    }

    public static void main(String[] args) {
        // Examples:
        System.out.println( calculateSqrt(  4   ) ); //  2
        System.out.println( calculateSqrt(  9   ) ); //  3

        System.out.println( calculateSqrt(  2   ) ); //  1.4142135623730951
        System.out.println( calculateSqrt(  0.5 ) ); //  0.7071067811865476
        System.out.println( calculateSqrt(  0   ) ); //  0
        System.out.println( calculateSqrt( -1   ) ); //  NaN
    }
}
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - Math.sqrt()

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join