Squaring a Number in Java

Cloudytechi
2 min readNov 15, 2021

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.

How to Square a Number in Java?

Squaring in java with 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();

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

putting 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)
{
System.out.println("Your entered value doesn't seem to be an integer!");
}

Remember to import the following code for the program to run as expected:

import java.util.InputMismatchException;
import java.util.Scanner;

create a separate function to square a number in Java, A way of doing so is:

public static int calcSquare(int number)
{
return number*number;
}

Call this method as:

int square = calcSquare(number);

Conclusion

There are two primary concerns to note here. The first is consistently handle the necessary exemptions so the program exits effortlessly. Second, it is desirable to accept the contribution as twofold or long rather than int to square a number in Java to apply the rationale for any number that the client enters. Attempt the above programs by changing the information type to twofold. Tell us about your outcomes.

--

--

Cloudytechi

A tech guy who is more enthusiastic of programming and love coding.