How to square a number in Java

Java math FAQ: How do I square a number in Java?

You can square a number in Java in at least two different ways:

  1. Multiply the number by itself.
  2. Call the Math.pow function.

Square a number by multiplying it by itself

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.

Square a number with the Math.pow method

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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.