top of page

How to Find Square Root of a Number in Java?

Here we will see Java program for finding square root using the API method.


package test;

import java.util.Scanner;

/**
 *
 * Java program to find the square root of a number in Java.
 * This Java program example demonstrates using Math class
 * sqrt() method to get the square root of a number in Java.
 *
 * @author java67
 */
public class SquareRoot{

 public static void main(String args[]) {
 
 //Used to get input number for which square root to find
 Scanner scanner = new Scanner(System.in);
 
 System.out.println("Enter number to find square root in Java : ");
 
 //getting input number from user to calculate square root
 double square = scanner.nextDouble();
 
 
 //getting the square root of a number in Java
 double squareRoot = Math.sqrt(square);
 
 //printing number and its square root in Java
 System.out.printf("Square root of number: %f is : %f %n" , square, squareRoot);
 
 }
 
}

Output:

Enter number to find square root in Java :
64
The square root of a number: 64.000000 is: 8.000000


This was our Java program to find the square root of a number in Java. It can find the square root of any floating-point number and you don’t need to only supply integers numbers. As I said use Java standard library methods to calculate square root but prepare with your own version of square root function if going for any programming interview.



Source: Java67


The Tech Platform

0 comments

Kommentare


bottom of page