It’s a very basic question not in terms of programming but in maths as well. In this post, we will learn how to square a number in Java using different ways.

We are going to use either:

  1. By multiplying the number with itself
  2. By using Math.pow()

Java 8 Arithmetic Exact Methods...!!! Click To Tweet

1. By multiplying the number with itself

It’s a traditional way of getting square of a number, just by multiplying the number by itself. Like below:

Square = number * number;

Example:

Output:

2. By using Math.pow()

java.lang.math class provides a method Math.pow() to get the square of a number. Like below:

Square = Math.pow(number,2);

Note: number is the first argument for which we want to create the square. the second argument is the power by which you are raising the number. To get the square, you need ‘2’ as the second argument. 

Example:

Output:

Note:

You might notice, why do we cast the Math.pow with (int) in above example. this is because the pow() method throws double primitive as it’s implementation. So, for us to convert it into ‘int’, we cast it with ‘int’. 

Additional Note:

Now, as you know how to square a number using Math.pow method just by powering it with number 2, similar to this if you are in need to power it with a different number you can do that by simply mentioning that number. Let’s say if you want to find the cube of a number then instead of using number 2, use 3. And, you are done.

I hope this article will help you in getting the square of a number with simplicity. 

Java 8 Arithmetic Exact Methods...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References: