How to Square a number In java

We will learn in this tutorial how to square a number in java . We can square in java using multiple methods . First we see what is squaring in java , then we will see example of square in java .

What is the square of a number?

In mathematics or algebra, you can calculate the “square” of a number, by multiplying the same number with itself.

Example : the square of 2 is (2*2=4)4, and the square of 3 is (3*3=9)9.

How to Square a number In java ?

Now we can square in java using these below methods .

  1. Square a number by multiplying it by itself
  2. Square a number using Math.pow function

1.  Square a number by multiplying it by itself

We can find square in java multiply number by itself .  It is very simple method for squaring in java for any  number .

public class SquareNumber {
	
	public static void main(String[] args) {
		int num = 2;
		int square = num * num ;
		System.out.println("square of num :"+ num +" is :"+ square );
	}
}

Output :

square of num :2 is :4

Square a number using Math.pow function

We can use Java math.pow() method for squaring in java . In this example of square  Math.pow(num, POW) multiply num with itself  POW times .

public class SquareNumber2 {
	
	public static final Integer POW = 2;
	
	//return square a number 
	public static Double getSquare(Double num) {
		//square a number
		return Math.pow(num, POW);
	}
	
	public static void main(String[] args) {
		double num = 2;
		System.out.println("square of num :"+ num +" is :"+ getSquare(num) );
		 num = 3;
		System.out.println("square of num :"+ num +" is :"+ getSquare(num) );
	}
}

Output :

square of num :2.0 is :4.0
square of num :3.0 is :9.0

In this tutorial we learned how to square a number in java using multiple methods. squaring in java is frequently ask question in academic exam . So you should try these example of square . You can find more java program for practice .

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 70 = 74