How to find the square of a number in java?

When we multiply a number by itself we call the product as the square of the number. Let us consider 2, the square of 2 is 4.

You can find the square of a number in java in the following two ways-

By multiplying the number by itself-

To multiply a number by itself in java, use the multiplication operator.

//finding square of an integer
int num = 4;
int square = num * num;
System.out.println(square);

//finding square of a double value
 double num = 4.2;
double square = num * num;
System.out.println(square);

Output-

16
17.64

Square a number using the math.pow() method-

The Math.pow() method is a built-in method and is used to calculate the power of a given number. To use the Math.pow() method in order to calculate the power of a number, you have to import the java.lang.Math package

This method accepts two arguments and returns the value of the first argument raised to the second argument. It returns the result of type double.

  • If the second argument is zero, then the result is 1.0.
  • If the second argument is 1.0 or 1, then the result is the same as the first argument.
  • If the second argument is NaN, then the result is NaN.
  • If the first argument is NaN and the second argument is nonzero, then the result is NaN (not a number).

Below is the code to calculate the square of a number using Math.pow() method-

public static void main(String[] args) {
  //Calculating 2^4 and casting the returned double result to int
  int sq1 = (int) Math.pow(2, 4);
  System.out.println("2^4 is " + sq1);
  //Calculating 1.2^2 and storing the returned double result to sq2
  double sq2 = Math.pow(1.2, 2);
  System.out.println("1.2^2 is " + sq2);
  //Calculating 10^2 and the returned double result is stored in a double variable 
  double sq3 = Math.pow(10, 2);
  System.out.println("10^2 is " + sq3);
}

Output-

2^4 is 16
1.2^2 is 1.44
10^2 is 100.0

    So these are the two ways in which you can find the square of a number.

    0 results
    Comment / Suggestion Section
    Point our Mistakes and Post Your Suggestions