๐Ÿ” Java How-To Examples
Estimated reading: 3 minutes 31 views

๐Ÿงฎ Java Program to Calculate Square Root โ€“ With Examples and Best Practices

๐Ÿงฒ Introduction

Calculating the square root is a common requirement in mathematical and scientific applications. Java provides a simple yet powerful way to calculate square roots using built-in methods from the Math class.

By the end of this guide, you’ll be able to:

  • โœ… Calculate square roots using Math.sqrt()
  • โœ… Handle invalid input like negative numbers
  • โœ… Build user-interactive and reusable Java programs

๐Ÿ“ What is Square Root?

The square root of a number x is a value y such that:

y ร— y = x

In Java, this is done using the built-in Math.sqrt() method.


๐Ÿ’ป Java Program โ€“ Hardcoded Input

public class SquareRootExample {
    public static void main(String[] args) {
        double number = 25;
        double result = Math.sqrt(number);

        System.out.println("Square root of " + number + " is: " + result);
    }
}

โœ… Explanation:

  • Math.sqrt(25) returns 5.0.
  • double is used for decimal precision.

๐Ÿ“ฅ Java Program โ€“ User Input with Scanner

import java.util.Scanner;

public class SquareRootUserInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        double number = scanner.nextDouble();

        if (number < 0) {
            System.out.println("Error: Cannot calculate square root of a negative number.");
        } else {
            double result = Math.sqrt(number);
            System.out.println("Square root of " + number + " is: " + result);
        }

        scanner.close();
    }
}

โœ… Explanation:

  • Takes user input.
  • Checks for negative values before computing square root.

๐Ÿ” Java Method โ€“ Reusable Function

public class SquareRootUtil {
    public static double computeSquareRoot(double number) {
        if (number < 0) {
            throw new IllegalArgumentException("Negative input is not allowed");
        }
        return Math.sqrt(number);
    }

    public static void main(String[] args) {
        double value = 16;
        System.out.println("Square root: " + computeSquareRoot(value));
    }
}

โœ… Best for modular code and reusability in larger projects.


โš ๏ธ Edge Case Warning

double result = Math.sqrt(-9); // NaN
System.out.println(result);   // Output: NaN

โš ๏ธ Math.sqrt() returns NaN (Not-a-Number) for negative inputs, not an exception. Handle it manually for cleaner logic.


๐Ÿ“‹ Sample Output

Enter a number: 36
Square root of 36.0 is: 6.0
Enter a number: -5
Error: Cannot calculate square root of a negative number.

๐Ÿ“Œ Summary

In this tutorial, youโ€™ve learned:

  • โœ… How to calculate the square root in Java using Math.sqrt()
  • โœ… Handle user input and negative numbers
  • โœ… Create reusable functions for cleaner code

This logic is widely used in geometry, physics, finance, and UI scaling.


โ“ FAQ โ€“ Square Root in Java

โ“Can I calculate square root of negative numbers?

No, not directly. Java returns NaN for negative inputs. Use Math.sqrt() with a manual check.

โ“Which data type is best for square root?

Use double for precision. Avoid int, as square roots often result in fractions.

โ“Is there a way to round the square root result?

Yes:

double result = Math.sqrt(50);
System.out.println(Math.round(result)); // Rounds to nearest whole number

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Square Root

Or Copy Link

CONTENTS
Scroll to Top