Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find square root of a number.

Java Code Example — Basic Programs

ADVERTISEMENT

Java Program to find square root of a number.

Objective

Write a Java program to find the square root of a given number.

Algorithm / Approach

  1. Take an integer as input from the user.
  2. Use the built-in Math.sqrt() method to find the square root.
  3. Store the result in a double variable.
  4. Print the square root.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 { 
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Number: ");
  int x = s.nextInt();
  double y = Math.sqrt(x);
  System.out.print("SQUARE ROOT = "+y);
 }
}

Expected Output

Enter Number: 5
SQUARE ROOT = 2.23606797749979

Explanation of the Program

  • The program uses the built-in Math.sqrt() method.
  • The integer input x is passed to the method to calculate its square root.
  • Since the result can be a decimal, it is stored in a double variable y.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Trying to assign the result of Math.sqrt() to an int without casting.
  • Not considering that square roots can have fractional values.
ADVERTISEMENT