Java math FAQ: How do I square a number in Java?
You can square a number in Java in at least two different ways:
Here’s how to square a number by multiplying it by itself:
i = 2 int square = i * i
In that case, if you print the value of
square, it will be 4.
Here’s how you call the
Math.pow method to square a number:
i = 2 int square = Math.pow(i, 2)
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 get the cube of a number, like this:
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.