Java 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.
I hope these examples of how to get the square of a number in Java have been helpful. As usual, if you have any questions or comments, just leave a note in the Comments section below.