Java Examples

Java Program - Square Root of a Number



If a number is multiplied by itself (n*n), the final number will be the square of that number and finding the square root of a number is inverse operation of squaring the number. If x is the square root of y, it can be expressed as below:

square root

Alternatively, it can also be expressed as:

x2 = y

Method 1: Using sqrt() method of Java Math Class

The sqrt() method of Java Math class can be used to return square root of a number.

import java.lang.Math;

public class MyClass {
  public static void main(String[] args) {
	double x = 16;
	double y = 25;

	//sqrt() takes double datatype as argument
	double x1 = Math.sqrt(x);
	double y1 = Math.sqrt(y);
	System.out.println("Square root of " + x + " is " + x1);
	System.out.println("Square root of " + y + " is " + y1);
  }
}

The above code will give the following output:

Square root of 16.0 is 4.0
Square root of 25.0 is 5.0

Method 2: Using pow() method of Java Math Class

The pow() method of Java Math class can also be used to calculate square root of a number.

import java.lang.Math;

public class MyClass {
  public static void main(String[] args) {
	double x = 16;
	double y = 25;
	
	//pow() takes double datatype as argument
	double x1 = Math.pow(x, 0.5);
	double y1 = Math.pow(y, 0.5);
	System.out.println("Square root of " + x + " is " + x1);
	System.out.println("Square root of " + y + " is " + y1);
  }
}

The above code will give the following output:

Square root of 16.0 is 4.0
Square root of 25.0 is 5.0