Select Page

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()

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’.