- How to Square a number In java
- What is the square of a number?
- How to Square a number In java ?
- 1. Square a number by multiplying it by itself
- Square a number using Math.pow function
- How to Compute Square in Java [Practical Examples]
- Using multiplication operator *
- Using Math.pow() function
- Using pow() of BigInteger Class
- Using Apache Commons Math API
- Examples to Compute Square in Java
- Example 1 : Computing Area of Circle
- Example 2 : Computing Area of Square
- Example 3 : Computing hypotenuse using Pythagoras Theorem
- Example 4 : Computing result of Series of square
- Summary
- Squares in Java
- How to calculate Square in Java?
- Example #1
- Example #2
- Example #3
- Example #4
- Example #5
- Conclusion
- Recommended Articles
- How to Square a Number in Java?
- How to Square a Number in Java?
- The Other Way to Square a Number in Java
- Conclusion
How to Square a number In java
We will learn in this tutorial how to square a number in java . We can square in java using multiple methods . First we see what is squaring in java , then we will see example of square in java .
What is the square of a number?
In mathematics or algebra, you can calculate the “square” of a number, by multiplying the same number with itself.
Example : the square of 2 is (2*2=4)4, and the square of 3 is (3*3=9)9.
How to Square a number In java ?
Now we can square in java using these below methods .
1. Square a number by multiplying it by itself
We can find square in java multiply number by itself . It is very simple method for squaring in java for any number .
public class SquareNumber < public static void main(String[] args) < int num = 2; int square = num * num ; System.out.println("square of num :"+ num +" is :"+ square ); >>
Square a number using Math.pow function
We can use Java math.pow() method for squaring in java . In this example of square Math.pow(num, POW) multiply num with itself POW times .
public class SquareNumber2 < public static final Integer POW = 2; //return square a number public static Double getSquare(Double num) < //square a number return Math.pow(num, POW); >public static void main(String[] args) < double num = 2; System.out.println("square of num :"+ num +" is :"+ getSquare(num) ); num = 3; System.out.println("square of num :"+ num +" is :"+ getSquare(num) ); >>
square of num :2.0 is :4.0 square of num :3.0 is :9.0
In this tutorial we learned how to square a number in java using multiple methods. squaring in java is frequently ask question in academic exam . So you should try these example of square . You can find more java program for practice .
How to Compute Square in Java [Practical Examples]
The square of a number is the product of the number times itself. In other words, a square is the result of multiplying any number by itself. Hence we can say for a number n, the square of a number will be result=n*n.
There are four different ways to compute square of a number in Java.
- Using multiplication operator *
- Using Math.pow() function
- Using BigInteger.pow() function
- Using Apache Commons Math API
Using multiplication operator *
This is the simplest approach to compute square of a number in Java. Here, we will use * operator to compute the square.
Example :In this example we are finding a square of an integer and a float number.
// Program to compute square of a number public class Main < public static void main(String[] args) < // Initializing a variable int i = 200; float f = 100.5f; // Computing a square and printing System.out.println("The square of a number " + i + " is " + (i * i)); System.out.println("The square of a number " + f + " is " + (f * f)); >>
The square of a number 200 is 40000 The square of a number 100.5 is 10100.25
Using Math.pow() function
In this approach, we will use pow() function of Math class of java.lang package to compute square of a number in Java. The pow() function returns the value of the first argument raised to the power of the second argument. This function accepts two double type parameter and returns a double value as a result. So, the problem with this approach is we cannot use it for integer or a float values.
Example :In this example we are finding a square of a double number using pow() function of Math class.
// Program to compute square of a number public class Main < public static void main(String[] args) < // Initializing a variable double d = 150.5; // Computing a square and printing System.out.println("The square of a number " + d + " is " + Math.pow(d, 2.0)); >>
The square of a number 100.5 is 10100.25
Using pow() of BigInteger Class
In this approach, we will use pow() function of BigInteger class of java.math package to compute square of a number in Java. The disadvantage of the Math.pow() function is they operate only on double values. However, if we want to compute square of a integer or long variable, we have to use pow() function of BigInteger Class. This function takes one parameter as an exponent.
Example :In this example we are finding a square of a integer and long variable. Her, we are using String.valueOf function to convert int and long variable to string type.
// Program to compute square of a number import java.math.BigInteger; public class Main < public static void main(String[] args) < // Initializing a variable int i = 110; long l = 2250; BigInteger b1 = new BigInteger(String.valueOf(i)); BigInteger b2 = new BigInteger(String.valueOf(l)); // Computing a square and printing System.out.println("The square of a number " + i + " is " + b1.pow(2)); System.out.println("The square of a number " + l + " is " + b2.pow(2)); >>
The square of a number 110 is 12100 The square of a number 2250 is 5062500
Using Apache Commons Math API
In this approach, we will need to download commons-math3-3.6.1-bin.zip from the url mentioned in the reference section. Thereafter, we have to add this jar to our existing project folder using the below given steps.
- Right click your project folder in eclipse
- Click on Build Path -> Add external archives
- Select the jar (commons-math3-3.6.1)from the extracted zip folder.
- You will see that jar added to Referenced Libraries
Example :In this example we are using ArithmeticUtils.pow() function that can accept long, int and BigInteger type of parameters.
// Program to compute square of a number import org.apache.commons.math3.util.ArithmeticUtils; public class temp < public static void main(String[] args) < long d = 1152; System.out.println("The square of a number " + d + " is " + ArithmeticUtils.pow(d, 2)); >>
The square of a number 1152 is 1327104
Examples to Compute Square in Java
Example 1 : Computing Area of Circle
// Program to compute Area of Circle import java.math.BigInteger; public class Main < public static void main(String[] args) < // Initializing a variable int r1 = 20; double r2 = 25.25; // Converting int to BigInteger BigInteger b1 = new BigInteger(String.valueOf(r1)); // Computing area of circle and printing b1 = b1.pow(2); long v = b1.longValue(); double res1 = 3.14159 * v; double res2 = 3.14159 * (Math.pow(r2, 2)); System.out.println("The Area of circle with radius " + r1 + " is " + res1); System.out.println("The Area of circle with radius " + r2 + " is " + res2); >>
The Area of circle with radius 20 is 1256.636 The Area of circle with radius 25.25 is 2002.959974375
Example 2 : Computing Area of Square
// Program to compute Area of Perfect Square import java.math.BigInteger; public class Main < public static void main(String[] args) < // Initializing a variable int side1 = 20; double side2 = 25.25; // Converting int to BigInteger and computing square BigInteger b1 = new BigInteger(String.valueOf(side1)); b1 = b1.pow(2); // Computing square double res2 = Math.pow(side2, 2); // Printing System.out.println("The Area of square with side " + side1 + " is " + b1); System.out.println("The Area of square with side " + side2 + " is " + res2); >>
The Area of square with side 20 is 400 The Area of square with side 25.25 is 637.5625
Example 3 : Computing hypotenuse using Pythagoras Theorem
The Pythagoras theorem equation is expressed as, c^2 = a^2 + b^2, where ‘c’ = hypotenuse of the right triangle and ‘a’ and ‘b’ are the other two legs.
// Program to compute hypotenuse public class Main < public static void main(String[] args) < double ab = 4; double ac = 3; double bc; // Computing result by applying Pythagoras theorem bc = Math.sqrt(Math.pow(ab, 2) + Math.pow(ac, 2)); System.out.println("The result of computation is " + bc); >>
The result of computation is 5.0
Example 4 : Computing result of Series of square
Here, we are computing 10^2 +11^2 + 12^2 + 13^2 + 14^2
// Program to compute series of square of numbers public class Main < public static void main(String[] args) < double x = 10; double sum = 0; double r; // Computing result of series for (int i = 0; i & lt; 5; i++) < // Computing square of a number r = Math.pow(x, 2); // Computing sum of squares sum = sum + r; System.out.println(r + " + "); x++; >System.out.println("The result of computation is " + sum); > >
100.0 + 121.0 + 144.0 + 169.0 + 196.0 + The result of computation is 730.0
Summary
The knowledge of computing square of a number in Java is very useful while working on a real time applications. In this tutorial, we covered four different approaches to compute square in Java. As per the requirement of an application, we can choose an appropriate approach for computation. We learned in detail about this approaches with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on computing a square of a number in Java.
Squares in Java
When a number is multiplied by itself, the resulting number formed is the Square of the Number. Squares of a number are very easy to find. Generally, whenever we find the square root of an Integer number, we only get the result in Integer. Similarly, whenever we find the square of a decimal number, we get the answer in decimal as well. An interesting fact about the square of a number is that whenever we do a square of an integer number, the value of the resulting number increases. However, when we do the square of decimals between 0 and 1, the resulting number decreases. An example would be that of a squaring of 0.5. When we square 0.5, the number gets decreased to 0.25. In this article, we are going to see the various methods of how we can square a number using the Java programming language.
Web development, programming languages, Software testing & others
Working – Square of a number can be found out in Java by a variety of techniques. We would like to see some examples related to the square of a number by which we can understand the square of a number better.
How to calculate Square in Java?
Let us learn how to calculate square in java:
Example #1
The simplest way of finding the square of a number is Math.pow(), where it can be used to calculate any power of a number.
import java.util.*; public class Square < public static void main(String args[]) < Scanner sc=new Scanner(System.in); int num; System.out.print("Enter a number which is integer format: "); num=sc.nextInt(); System.out.println("The square of "+ num + " is: "+ Math.pow(num, 2)); >>
Example #2
In the next program, we are going to calculate the square of a number in the usual form such that it multiplies two numbers sequentially and finds the square of the respective number.
import java.util.*; public class Square2 < public static void main(String args[]) < Scanner sc=new Scanner(System.in); int no; System.out.print("Enter a number which is integer format: "); no=sc.nextInt(); System.out.println("Square of "+ no + " is: "+(no*no));//the number is multiplied with its own >>
Example #3
In this example, we are going to check if a number is a perfect square or not. This is a little bit complex program as it checks if a number is a square of another number.
import java.util.Scanner; class JavaExample < static boolean checkPerfectSquare(double x) < // finding the square root of given number double s= Math.sqrt(x); return ((s - Math.floor(s)) == 0); //Math.floor() is used here to calculate the lower value. >public static void main(String[] args) < System.out.print("Enter any number:"); Scanner scanner = new Scanner(System.in); double no= scanner.nextDouble(); scanner.close(); if (checkPerfectSquare(no)) System.out.print(no+ " is a perfect square number"); else System.out.print(no+ " is not a perfect square number"); >>
Example #4
In this program, we find the number of square numbers within a specific range. We enter the range of numbers, and the code would produce the square number in that specific range. In the below program, we find the number of square integers between 0 and 100.
// Finding the range of perfect square numbers in Java programming language import java.io.IOException; public class SquareNumbersInRange < public static void main(String[] args) throws IOException < int starting_number = 1; int ending_number = 100; System.out.println("Perfect Numbers between "+starting_number+ " and "+ending_number); for (int i = starting_number; i > > >
Example #5
In this program, we are going to see the sum of squares of the first N natural numbers. We enter the value of N, and the program calculates the sum of squares of the first N natural numbers.
// Java Program to find sum of // square of first n natural numbers import java.io.*; class SumofSquares < // Return the sum of the square of first n natural numbers static int square sum(int n) < // Move the loop of I from 1 to n // Finding square and then adding it to 1 int sum = 0; for (int i = 1; i // Main() used to print the value of sum of squares public static void main(String args[]) throws IOException < int n = 6; System.out.println("The sum of squares where N value is 6 is "+ squaresum(n)); >>
Conclusion
- In this article, we see a list of methods by which we can square a number, find whether a number is square or not within a specific range, and the sum of integers of the first N natural numbers. However, there are also some other techniques that can be used to find the square of a number. The name of a technique that can be used to see and check if a number is square or not is the Recursion technique, which uses a function to check if the number is a perfect square.
- Although the recursion technique is difficult to use, it can be used to calculate the square of a number within a few lines of code. Further, using square numbers, we can generate a lot of pattern programs. We can print a square pattern in a spiral format or a zig-zag format. Similarly, the square numbers can be used in the source code to generate the double square, such as the number 16, where the double square is number 2.
Recommended Articles
This is a guide to the Squares in Java. Here we have discussed the Introduction along with Examples and codes with Output of Squares in Java. You can also go through our other suggested articles to learn more–
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access
1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access
3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access
How to Square a Number in Java?
There are many ways to square a number in Java, the simplest of which is multiplying the number by itself. There are also utility methods to do the same. If your project needs to do this often, you can build a function and call the utility as well. We will also see how this utility method can do square, cube, and more operations on a number.
How to Square a Number in Java?
The first and simplest method is to multiply the number by itself, as shown below:
int number = 2; int square = number*number; System.out.println(square);
Simple and sweet, isn’t it? Just for the sake of fun, let us take the input from a user:
int number = new Scanner(System.in).nextInt();
We have used Scanner to get the input from the user. Users can put any values like 2 and 3. Users can also enter 2.3 or any other decimal number, but in this case, the program will throw an exception! This is what makes this program a bit more complex. We should put a try/catch to handle:
Exception in thread "main" java.util.InputMismatchException
And put a message to the user to enter only integer values:
System.out.println("Enter an integer to get its square:"); try < int number = new Scanner(System.in).nextInt(); int square = number*number; System.out.println(square); >catch(InputMismatchException time)
Remember to import the following code for the program to run as expected:
import java.util.InputMismatchException; import java.util.Scanner;
We can also create a separate function to square a number in Java, which can then be called by any class. A way of doing so is:
public static int calcSquare(int number)
int square = calcSquare(number);
The Other Way to Square a Number in Java
The second way to square a number in Java is to use the math utility function pow. Math.pow() works only with double, because that covers integers too; however, if we have to use the int data type, we have to typecast the return value. For example:
int number2 = new Scanner(System.in).nextInt(); int square2 = (int) Math.pow(number2, 2); System.out.println(square2);
We have to put the same try/catch block here as well. Note that this function can be generalized to get any power by changing the second parameter of the function:
int square2 = (int) Math.pow(number2, 5); So, if our number2 is 2, the output will be 2 raised to the power 5 = 32.
Conclusion
There are two main points to note here. The first is always handle the required exceptions so that the program exits gracefully. Second, it is preferable to take the input as a double or long instead of int to square a number in Java so that we can apply the logic for any number that the user enters.
Try the above programs by changing the data type to double. Let us know about your results and understanding of Java square.
People are also reading: