cube

How to square a number in Java

Java 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.

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:

Syndicate content