Java sqrt() method with Examples

Java 8Object Oriented ProgrammingProgramming

The java.lang.Math.sqrt(double a) returns the correctly rounded positive square root of a double value. Special cases −

  • 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.

Following is an example to implement the sqrt() method of the Math class in Java −

Example

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      // get two double numbers numbers
      double x = 9;
      double y = 25;
      // print the square root of these doubles
      System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
      System.out.println("Math.sqrt(" + y + ")=" + Math.sqrt(y));
   }
}

Output

Math.sqrt(9.0)=3.0
Math.sqrt(25.0)=5.0

Example

Let us now see another example to implement the sqrt() method with negative and other value −

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      // get two double numbers numbers
      double x = -20.0;
      double y = 0.0;
      // print the square root of these doubles
      System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
      System.out.println("Math.sqrt(" + y + ")=" + Math.sqrt(y));
   }
}

Output

Math.sqrt(-20.0)=NaN
Math.sqrt(0.0)=0.0
raja
Published on 24-Sep-2019 08:36:59
Advertisements