Java Programs

Calculate Square root of Number

In this tutorial, we will learn how to write a Java program to calculate the square root of a given number Our program takes a number from the users as input and returns the square root of that number as output.

What is the square root of a number?

The square root can be defined as a factor of a number that, when multiplied by itself, gives the original number.

For example

2 is a square root of 4. -2 is also a square root of 4.

because 2*2 = 4 and -2 * -2 = 4

Calculate the square root of a number

import java.util.*;

public class Main
{
    public static void main(String[] args) {
        double num,cube;
        Scanner sc = new Scanner(System.in);
        System.out.println("Please give a number to calculate Square root" );
        num= sc.nextDouble();
        System.out.println("Square Root of "+num+" is ");
        System.out.printf("%.2f",Math.sqrt(num));
    }
}

Explanations

For input 25, the output generated by our program is math.sqrt(25.0) which is equal to 5.00.

Output

Please give a number to calculate Square root
25
Square Root of 25.0 is 
5.00

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs