Java math FAQ: How do I square a number in Java?
You can square a number in Java in at least two different ways:
- Multiply the number by itself
- Call the Math.pow function
The following examples demonstrate these approaches.
1) Square a number by multiplying it by itself
This is how you square a number by multiplying it by itself:
int i = 2; int square = i * i;
In this example if you print the value of
square, it will be 4.
2) Square a number with the Math.pow method
Here’s how you call the
Math.pow method to square a number:
int i = 2; int square = Math.pow(i, 2);
More power multipliers
In general I just multiply the number by itself to get the squared value, but the advantage of the
Math.pow method is that once you know how to use it, you can easily cube a number like this:
int i = 2; int square = Math.pow(i, 3);
Therefore, it’s helpful to know both approaches.
In summary, if you wanted to see a couple of ways to square a number (int, float, double, etc.) in Java, I hope this is helpful.