Java Program to Find Square Root of a Number - Example Code

Java program for a square root or a number in Java
How to write a Java program to find the square root of a number is a common Java programming exercise that many institute use in there Java course along with Java program to print Fibonacci series and How to find Armstrong numbers in Java, which we have seen earlier.  Java program for square root is also a popular question during college semester exams and various programming tests. If you are familiar with Java API then writing a Java program that can find the square root of a number using java.lang.Math class is not difficult. You just need to pass a double value and it returns a double which is the square root of the number you passed.  

In the next section, we will see the complete code example of finding the square root of a number from the Java program. Another Java coding questions which is very popular and related to programming exercise is writing Java program to find prime numbers, if you are going to appear in Java interviews than its worth looking.



How to find Square root of a number in Java

As I said it's easy to calculate square root using java.lang.Math sqrt() function but things can be a tricky question if the interviewer will ask you to write your own sqrt() function during programming interviews, well its not that easy to write sqrt() function which can operate on double but one trick I use to remember the concept that square of the square root must be either less than or equal to the number, you can use that concept to write your own sqrt() method in any programming language including Java. 

Barring Java interviews, I suggest programmer use standard JDK library or open-source library like Spring, Apache etc for such common task because of the quality of code and amount of testing done of those libraries. 

Btw, a basic knowledge of data structure and algorithms is needed and if you need to brush up then do so. If you need a resource, I highly recommend checking out Data Structures and Algorithms: Deep Dive Using Java course on Udemy. It's a hands-on course and covers all essential data structures. 

It's also very affordable and you can get in just $10 on Udemy flash sales which happens every now and then.

Java program to find square root of number - Example Code


Java program to find the square root of a number

Anyway, 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.

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass
Grokking the Coding Interview: Patterns for Coding Questions


Related Data Structure and Algorithm Interview Questions from Javarevisited Blog
  • Top 30 Array Coding Interview Questions with Answers (see here)
  • How to reverse an array in place in Java? (solution)
  • Top 15 Data Structure and Algorithm Interview Questions (see here)
  • How to find a missing number in an array? (answer)
  • Write a Program remove duplicates from an array without using Collection API? (program)
  • How to reverse String in Java without using API methods? (Solution)
  • Write a method to remove duplicates from ArrayList in Java? (Solution)
  • How to check if a number is binary in Java? (answer)
  • How to compare two arrays in Java? (answer)
  • Top 20 String coding interview questions (see here)
  • 50+ Data Structure and Algorithms Problems from Interviews (questions)
  • How to remove duplicate elements from an array in Java? (solution)
  • How to find all pairs whose sum is equal to a given number in Java (solution)
  • Top 30 linked list coding interview questions (see here)
  • Top 50 Java Programs from Coding Interviews (see here)
  • 5 Free Data Structure and Algorithms Courses for Programmers (courses)
  • 10 Algorithms Books Every Programmer Should Read (books)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • 100+ Data Structure Coding Problems from Interviews (questions)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you. As always suggestions, comments, innovative and better answers are most welcome.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free and all you need to do is create a free Udemy account to enroll in this course. 

10 comments:

  1. In mathematics, a square root of a number a is a number y such that y2 = a, or, in other words, a number y whose square (the result of multiplying the number by itself, or y × y) is a.

    ReplyDelete
  2. Write a Java program to find Square root of a number is common programming exercise for beginners in Java. Some people use it as practice and homework exercise to learn Java programming and
    get familiar with Java API in particular java.lang.Math, which holds key method for various mathematical tasks.

    ReplyDelete
  3. LET SOMEONE CORRECT THIS FOR ME. THANKS

    //java program for dept...........
    //group 9
    //serial no 44
    //name1:
    //name2:
    //name3:
    //name4
    //name5
    import javax.swing.JOptionPane;
    public class CSCGP9 {
    public static void main (String [] args){
    float z, zl, c=0.0f ;
    system.out.printLn ("S/N \t number \tsquare \tcube")n;
    for(int k = 1; k<= 9; k++){
    c=Float.parseFloat (JOptionpane.showInputDialog("Enter a number",0));
    z=square(c);
    zl=cube (c);
    system.out.println(k+"\t"+c+"\t"+square(c)+"\t"+cube(c));
    }
    }
    static Float square (float x){
    return x*x;
    }
    static Float cube (float x){
    return x*x*x;
    }
    }


    ReplyDelete
  4. C:\Users\student\Desktop\19>javac Sqr2.java
    Sqr2.java:10: error: possible loss of precision
    float r=Math.sqrt(square);
    ^
    required: float
    found: double
    1 error how to overcome this???

    ReplyDelete
    Replies
    1. Hello @Annonymous, Math.sqrt() returns double, which is bigger data type than float hence you cannot store a double value to float variable. if you want you can use the cast operator e.g.

      float r= (float) Math.sqrt(square);

      This will fix the problem.

      Delete
    2. You can change the float into double type.

      Delete
  5. Java program for finding nth root

    ReplyDelete
  6. Its too big see this is a very small one
    import java.util.*;

    /*Java Program to find square, square root and cube of a given number*/
    public class j5
    {
    public static void main(String args[]){
    Scanner sc=new Scanner(System.in);
    int num;

    System.out.print("Enter an integer number: ");
    num=sc.nextInt();

    System.out.println("Square of "+ num + " is: "+ Math.pow(num, 2));
    System.out.println("Cube of "+ num + " is: "+ Math.pow(num, 3));
    System.out.println("Square Root of "+ num + " is: "+ Math.sqrt(num));
    }
    }

    ReplyDelete
  7. This is without using any math functions

    import java.util.Scanner;

    public class SquareRoot {

    public static void main(String[] args)
    {

    System.out.println("Enter the number to find the square root");
    Scanner scr = new Scanner(System.in);
    int Sqt=scr.nextInt();

    for (int i=1;i<=Sqt;i++)
    {
    int reminder = Sqt%i;
    if (reminder==0 && (Sqt/i)==i)
    {
    System.out.println("The Square root of "+Sqt+" is = "+i);
    }
    }

    scr.close();
    }
    }

    ReplyDelete