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()
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
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:
1 |
Square of Number 5: 25 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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:
1 |
Square of Number 5: 25 |
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: