Post Views: 2,547

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:

- By multiplying the number with itself
- 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:**

| public class Square_a_number_Java_1 { public static void main(String[] args) { int number = 5; int squareOfNumber = number * number; System.out.println("Square of Number 5: "+squareOfNumber); } } |

**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:

| public class Square_a_number_Java_2 { public static void main(String[] args) { int number = 5; int squareOfNumber = (int) Math.pow(number, 2); System.out.println("Square of Number 5: "+squareOfNumber); } } |

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

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

### Other Useful References:

Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.
He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

View all posts

http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak