Java: How to square a number

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

Solution

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

The following examples demonstrate these solutions.

Note that this same solution also works for Kotlin.

Solution 1) Java: 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.

Solution 2) Java: 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 Java 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 cube a number like this:

int i = 2;
int square = Math.pow(i, 3);

Because this lets you calculate multiple powers of multiplication, 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.