The square of a number is the product of that number with itself. In Java, there are various approaches that developers can use for squaring a number. These approaches include built-in libraries, multiplication operator “*”, and functions. However, between these different approaches, the concept of fast retrieval of results draws the line.
This article presents a practical demonstration of different methods for taking a square of a number in Java.
How to Square a Number in Java?
There are multiple applications of square functionality in Computer Science such as calculating distance, or areas in various algorithms and data structures. Three different methods in Java are used for taking a square. These methods include multiplying the number with itself, by using the functions, or by using the BigInteger class.
Method 1: Square a Number by Multiplying It With Itself
One of the simplest approaches is to multiply the number by itself using the asterisk (*). In this section of the article, we will discuss this approach by using predefined integer values and by taking input from the user
Case 1: Square a Number by Using Defined Values
The code given below demonstrates a simple use case for calculating the square of a number:
public class squareDigit {
public static void main(String[] args) {
int number=2;
System.out.println("Square of the number is = " + number * number);
}
}
Within the above-mentioned code:
- The class “squareDigit” contains the “main()” method. Within the main() method, declare an integer-type variable “number” and initialize it with the value “2”.
- The statement “System.out.println()” displays the resultant value on the console. Within this line of code, the “number * number” multiplies the number by itself.
Output
Case 2: Square a Number by Using User Input
Consider a case where the user inputs a specific value for calculating the square. For this purpose, the code is mentioned as follows:
package SquarePackage;
import java.util.*;
public class squareDigit {
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter an integer number e.g. 2,3...");
int number=input.nextInt();
System.out.println("Square of the number is " + number * number );
}
}
Within this code:
- The “import java.util.*” imports all the libraries and functions from the “util” package such as Scanner Class.
- Inside the main method, the Scanner class initializes the object “input”. The “System.in” specifies that the input is to be entered from the keyboard.
- The “System.out.println()” prompts the user to enter an integer number.
- The integer variable “number” will store the user input. The nextInt() is a method of the Scanner class and is used for taking the numeric input from the user. The double value entered by the user will result in the “InputMismatch Exception” which is discussed later in this article.
- Finally, the last line of code multiplies the number with itself as given by the user. The square of the number is then displayed in the output window.
Output
Method 2: Square a Number by Using Functions
To square a number, built-in and user-defined functions can be used. The built-in methods include “Math. pow()” and “mulitplyExact()”. On the other hand, the user-defined functions can implement the same functionality along with additional requirements. This section of the article discusses the calculation of a square of a number by using the Math.pow(), multiplyExact(), or user-defined functions.
Case 1: Square a Number Using Math.pow() Function
The first function we have in the built-in category is the “Math.pow()” function. The “Math. pow()” function accepts and returns the double value.
Syntax
The syntax is given as follows:
public double pow(double base, double exponent)
In the above-mentioned syntax:
- The “base” is the number that is to be multiplied by itself.
- The “exponent” specifies the total number of times to multiply the base with itself.
Other than square, the Math.pow() function can be used to calculate the power of the value specified. For this demo, we are using this function to calculate the square as shown in the code below:
public class squareDigit {
public static void main(String[] args) {
System.out.println("Square of number is " + Math.pow(5, 2));
System.out.println("Square of number by Type casting is " + (int) Math.pow(5, 2));
}
}
In the above-mentioned code:
- The “Math.pow(5, 2)” specifies that the value 5 will be multiplied by itself two times within the first print statement.
- Within the second print statement, the (int) Math.pow(5,2) converts the result of Math.pow() to an integer. This phenomenon is known as typecasting.
Output
Case 2: Square a Number by multiplyExact() Function
The “Math.multiplyExact()” method multiples the two numbers and returns the product. For this tutorial, this function can also be used to calculate the square in Java.
Syntax
The syntax of the function is given as follows:
Math.multiplyExact(value1, value2);
Within the above-mentioned syntax:
- The “value1” and “value2” are the two arguments for this function whose product is to be returned. The int and long are two datatypes to be used with this function.
Given below is the code for calculating the square using the multiplyExact() method:
public class squareDigit {
public static void main(String[] args) {
int number = 5;
System.out.println("Square of the number is " + Math.multiplyExact(number, number));
}
}
In the above-mentioned code:
- The “number” is an integer variable which is initialized with the value “5” inside the main method of the squareDigit class.
- The print statement is used to display the output by calling the multiplyExact() function of the Math class. The multiplyExact() method multiplies the number with itself to generate the square of the number.
Output
Case 3: Square a Number by User-defined Function
User-defined functions are a block of code provided by the user to perform a specific task. In Java, squaring of a number can be achieved by using custom functions (user-defined). Given below is a user-defined function to take a square of a number:
public class squareDigit {
public static int takeSquare(int number)
{
int square=0;
for (int i=1;i<=number; i++)
{
square+=number;
}
return square;
}
public static void main(String[] args) {
int number= 6;
System.out.println("The square is " + takeSquare(5));
}
}
Within the above code:
- Inside the sqaureDigit class, a custom method “takeSquare()” is defined that accepts an integer value. A numeric value is returned as a result after calculations.
- An integer “square” is initialized with the value “0” inside the takeSqaure() method.
- Next, a for loop is used for calculating the square of the number. The iterations start from “i=1” and will continue to iterate until the value of “i” is less than or equal to the given number.
- In each iteration, the value of “number” will be added to the “square” variable for taking a square. The number will continue to be added to the “square” variable until the condition (i<=number) is met.
- When the loop terminates, the “return” statement is used to return the “square” variable.
- Finally, a print statement displays the output after the “takeSquare()” calculates the square of value “5”.
Output
Method 3: Square of a Number Using BigInteger Class
The BigInteger class in Java is used to perform calculations on huge numeric values. Such values cannot be accommodated in long and int data types. This is where the BigInteger class comes in handy. Given below is the code to use BigInteger Class for calculating square:
import java.math.BigInteger;
public class squareDigit {
public static void main(String[] args)
{
BigInteger number1=new BigInteger("123456789123456789");
BigInteger square=number1.multiply(number1);
System.out.println("Square of the Value is " + square);
}
}
In the above-given code:
- The “import java.math.BigInteger” statement includes the BigInteger class and its functions.
- Within the main function, the BigInteger class initializes the object “number1” with the value specified passed in it.
- The variable “square” is of BigInteger data type to store the square. The “number1” variable is multiplied with itself for squaring using the multiply function of the BigInteger class.
- Finally, the print statement is used for displaying the output.
Output
Bonus Tip: How to Fix the InputMismatch Exception in Squaring a Number?
The InputMismatch Exception is thrown for the invalid input. Consider a case where the user gives a decimal value instead of an integer value for calculating the square. The value cannot be stored in the integer variable and It will throw the InputMismatch exception at runtime as shown below:
To resolve this exception, typecasting can be used. The code given below functions for the decimal as well as integer values:
import java.util.Scanner;
public class squareDigit {
public static void main(String[] args) //main function that contains the code
{
Scanner myobj=new Scanner(System.in); //myobj is the object of the Scanner class
System.out.println("Enter an integer number e.g. 2,3...");
int number=(int) myobj.nextDouble();
System.out.println("Square of the number is " + number*number );
}
}
In the above-mentioned code:
- The “(int) myobj.nextDouble()” statement accepts both integer and double values. The decimal values are converted into integers by rounding off the values. However, the integer values are calculated as it is.
Output
Conclusion
To square a number in Java, multiply the value by itself, use the built-in methods, or the BigInteger class as shown in this article. Multiplying the number with itself is the simplest approach but it can be problematic when dealing with big numbers. While the built-in methods include Math.pow() and multiplyExact() functions from the Math class serve the same functionality. Similarly, the multiply function of the BigInteger class is also used to calculate the square of huge numbers. This article provides a practical demonstration of calculating the square in Java.