- Case Study using Tableau, Python and SQL
- Introduction to Tableau
- Data Science in E-commerce
- Introduction to Natural Language Processing
- Linear Algebra for Analysis
- Advanced SQL: Functions and Formulas
- Introduction to Database Design with MySQL
- Unsupervised Learning: Clustering
- Linear Regression - Step by Step Guide

- Introduction to Modern Public Relations
- Creating Consumer Value through Effective Marketing
- Build Successful Celebrity Partnerships & Campaigns
- Influencer Marketing from a Brand's Perspective
- Introduction to Advertising
- Getting Influencer Marketing Right
- Complete Guide to Content Marketing
- Ultimate Guide to Email Marketing
- Basics of Search Engine Optimization

- How to be a Successful Business Analyst
- Introduction to Design Thinking
- Investing in the Modern Era
- Introduction to International Business Environment
- Introduction to Entrepreneurship
- Digital Innovations in the Financial System
- Introduction to FinTech
- Introduction to HR Analytics
- Introduction to Research Methodology

Tutorial Playlist

176. # Square Root in Java

Content

Square and square root in Java are some basic topics taught to students when they start coding. Although it is an easy task to perform, students might get stuck in the beginning. Here is a complete guide on performing square and square roots in Java with the help of different methods. Learning these basic functions in Java is important because squaring and square rooting a number can apply to various algorithms and mathematical operations.

Squaring a number means multiplying it by itself. Java has an operator for this purpose - the multiplication sign (*).

On the contrary, a square root of a number is a value that, when multiplied by itself, gives back the original number.

Squaring a number means multiplying that number by itself. Here we raise a number to the power of 2.

For instance, on squaring the number 4, we get 4 x 4 = 16. Similarly, on squaring the number -3, we get (-3) x (-3) = 9. This happens because we get a positive result by multiplying two negative numbers.

We can also represent squaring in mathematical notation using an exponent of 2. So, instead of writing "3 times 3", we can write "3 raised to the power of 2" or "3^2".

Square rooting a number is the inverse of squaring in mathematics. In other words, what number must be multiplied by itself to get a given number?

Here is an example for you to understand it better:

The square root of 9 is 3 since 3 x 3 = 9. In the same way, the square root of 16 is 4 since 4 x 4 = 16.

We use the symbol √ to denote a square root. For example, √9 = 3, and √16 = 4.

Here are two methods that you can use to square a number in Java. The first method is multiplying the number by itself, and the second is using the Math. pow method.

The first way to square in Java is to multiply the number by itself. You can use the * operator (asterisk) to perform this task in Java.

**Here's an example code for a better understanding:**

public class Main {

public static void main (String[] args){

int number = 6;

int result = number * number;

System.out.println(result);

}

}

This code should give you an output value of 36.

In the above example, we first decide on a variable “number.” Then assign it the value of “6”. Then multiply the “number” (6) by itself using the “*” operator. Then assign the result to a new variable known as the “result.” Finally, the “System.out.println()” method is used to print the result to the console.

Another way you can square a number in Java is by using the Math.pow function. This function takes two arguments: the base and the exponent.

**Here is an example of the code:**

public class Main {

public static void main (String[] args){

double number = 4.5;

double result = Math.pow(number, 2);

System.out.println(result);

}

}

The code would print an output value of 20.25.

In this example, we first declare a variable called “number.” Then assign it the value of “4.5”. Then use the Math.pow() function to raise the “number” (4.5) to the power of 2. This is equivalent to squaring it. We then assign the result to a new variable called “result.” Then “System.out.println()” is used to print the result to the console.

Note that we have used the “double” command before “number” as well as “result.” The purpose of the “double” command is to allow performing multiplication with decimal values. If you want to multiply with the help of integers, you can use the “int” command instead.

There are three ways of finding a square root in Java. The first is, Math.sqrt(), Math. pow, and the final one, by not using any inbuilt function.

One way to calculate the square root of a number in Java is by using the Math.sqrt() function. This function takes a single argument: the number whose square root you wish to find out.

**Here is an example of the code:**

public class Main {

public static void main (String[] args){

double number = 25;

double result = Math.sqrt(number);

System.out.println(result);

}

}

The code would print an output value of 5.0.

In the above example, we first declare a variable called “number.” Then assign it the value of “25”. Then use the Math.sqrt() function to calculate the square root of “number.” Then assign the result to a new variable called “result”. Then “System.out.println()” prints the result to the console.

Note that we have again used the “double” command before “number” as well as “result” to be able to work with decimal values. If you want to multiply with integers, you can use the “int” command instead.

You could use the Math.pow() function to find out the square root of a number. We can do it by raising it to the power of 0.5.

**Here is an example:**

public class Main {

public static void main (String[] args){

double number = 16;

double result = Math.pow(number, 0.5);

System.out.println(result);

}

}

The code would print an output value of 4.0.

In this example, we label a variable as a “number.” Then it assigns it the value of “16”. After this, we use the Math.pow() function to raise the “number” (16) to the power of “0.5”.

This equates to calculating the square root of “number”. After this, we assign the result to a new variable called “result.” Then “System.out.println()” prints the result to the console.

You can also calculate the square root in Java without the sqrt functions. In that case, you will have to use the Babylonian method. We run a series of calculations to achieve the desired level of accuracy with the help of this method.

**Here is an example code snippet:**

public class Main {

public static void main(String[] args) {

double number = 64.0;

double result = sqrt(number);

System.out.println("The square root of " + number + " is " + result);

}

public static double sqrt(double number) {

double guess = number / 2;

double prevGuess;

do {

prevGuess = guess;

guess = (guess + number/guess) / 2;

} while (Math.abs(guess - prevGuess) > 0.00001);

return guess;

}

}

In this example implementation, we first declare a method called “sqrt.” This takes a single argument, “number”. Then initialize a variable called “guess” to the value of “number” / 2. This is our initial estimate for the square root of “number.” Then we use a do-while loop to refine our estimate. This is continued until the difference between our current and previous estimates is less than a specified tolerance of 0.00001.

Within the loop, we first store our current estimate in a variable called “prevGuess.” Then update our estimate using the formula “(guess + number/guess) / 2”. This is the Babylonian method for improving our estimate of the square root of “number.” Until we reach a sufficiently accurate estimate, the iteration is continued. After which, the final value of “guess” is returned as the output. Note that we used the “Math.abs()” function to calculate the absolute value of the difference between “guess” and “prevGuess.”

In mathematics, a perfect square number is an integer that is the square of some other integer. This means we get a perfect square in Java by multiplying one integer by itself.

For instance, the integers: 1, 4, 9, 16, 25, and 36 are perfect squares because they are the squares of 1, 2, 3, 4, 5, and 6, respectively. One property of a perfect square is that the square root of a perfect square is always an integer.

Among its many uses, perfect squares can be used in geometry to calculate the areas of squares and in algebra to factor quadratic expressions.

**Example 1: Calculating the square root of a number**

public class Main {

public static void main(String[] args) {

double number = 25;

double squareRoot = Math.sqrt(number);

System.out.println("The square root of " + number + " is " + squareRoot);

}

}

In this code example, we first label a variable called “number.” Then assign it the value of “25”. This is the number we want to calculate the square root of. Then use the “Math.sqrt()” method to calculate the square root of “number.” After this we assign the result to a variable called “squareRoot”.

Then we use “System.out.println()” to print a message to the console with the expected output. In this case, it displays the original number and its square root. Here, you should get the following output:

The square root of 25.0 is 5.0

**Example 2: Calculating the hypotenuse of a right-angled triangle**

public class Main {

public static void main(String[] args) {

double side1 = 3.0;

double side2 = 4.0;

double hypotenuse = Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));

System.out.println("The hypotenuse of the triangle is " + hypotenuse);

}

}

In this example again, we first label two variables called “side1” and “side2”. These are the lengths of the two sides of a right triangle. Then use the “Math.pow()” function to calculate the square of each side. The next step is to add them together to get the sum of their squares.

We pass this sum as an argument to the Math.sqrt() function. This calculates the square root of the sum. After this, it assigns it to a variable called “hypotenuse.” Then “System.out.println()” command is used to print a message to the console. The output displays the length of the hypotenuse and shows as follows:

The hypotenuse of the triangle is 5.0

This output confirms that the Math.sqrt() method correctly calculated the length of the hypotenuse of the right triangle with sides of length 3 and 4 units.

**Example 3: Calculating the distance between two points in a 2D coordinate system**

public class Main {

public static void main(String[] args) {

double x1 = 2.0;

double y1 = 3.0;

double x2 = 5.0;

double y2 = 7.0;

double distance = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));

System.out.println("The distance between (" + x1 + ", " + y1 + ") and (" + x2 + ", " + y2 + ") is " + distance);;

}

}

We label the variables first as “x1”, “y1”, “x2”, and “y2” in this example. These denote the x and y coordinates of two points in a 2D coordinate system.

Following this, we use the Math.pow() method to calculate the squares of the differences between the x-coordinates and the y-coordinates. We then add them together and take the square root of the sum to get the distance between the two points.

We then assign this distance to a variable labeled as ‘distance.’ ‘System.out.println()’ prints a message to the console. This displays the coordinates of the two points and the distance between them. The output is as follows:

The distance between (2.0, 3.0) and (5.0, 7.0) is 5.0

This output confirms that the Math.sqrt() method calculated the distance between the two points (2, 3) and (5, 7) efficiently in the two-dimensional coordinate system.

**Example 4: Calculating the square root of a number in Java using for loop.**

public class Main {

public static void main(String[] args) {

double number = 25.0;

double result = sqrt(number);

System.out.println("The square root of " + number + " is " + result);

}

public static double sqrt(double number) {

double result = 1.0;

for (int i = 0; i < 10; i++) {

result = (result + number / result) / 2.0;

}

return result;

}

}

In this example, we used the sqrt function to initialize a “result” variable to 1.0.

This is a reasonable initial guess for the square root. It then enters a loop that repeats a fixed number of times. We do it 10 times in this example. Then it refines the guess by calculating the average of the “guess” and “number/guess” in each iteration. The output is as follows:

The square root of 25.0 is 5.0.

Square and square root in Java are quite simple to learn. But they must not be neglected just because they are simple. They are equivalent to the basics of any subject. If you want to be a programmer, you must be adept in Java. Square and square root will give you a headstart in that direction. You can enroll in a professional course to master the language better.

**1. What is the Math.sqrt() method in Java?**

The Math.sqrt() method is a built-in function in Java. This function is used to calculate the square root of a given number.

**2. Can the Math.sqrt() method return negative values?**

The Math.sqrt() method always returns a non-negative value. However, if you try to use this function with negative values, it will return NaN (not a number) as the output.

**3. What is the difference between Math.sqrt() and Math.pow() functions in Java?**

The Math.sqrt() function is used to calculate the square root of a given number. Whereas the Math.pow() is used to raise a given number to a specified power.

PAVAN VADAPALLI

popular

+91

Talk to our experts. We’re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .