We can square a number in Java in no less than two different ways. Let have a look on each method one by one.
Method1: Multiplying the Number by Itself
To square a number x, we can multiply the number by itself.
Y = x * x.
Java Program for the above method.
import java.util.Scanner; public class Square { public static int returnSquare(int num) { return num*num; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter a number: "); // This method reads the number provided using keyboard int num = scan.nextInt(); // Closing Scanner after the use scan.close(); // Squaring the number int square = returnSquare(num); // Displaying the Square System.out.println("The Square of the number is : " + square); } }
Output:
Enter a number: 5
The Square of the number is : 25
Method 2: Using the Math.pow() Function
Lets have a look how we can find square of number in java using Math.pow() function.
import java.util.Scanner; import java.lang.Math; public class Square { public static double returnSquare(double num) { return Math.pow(num, 2); } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter a number: "); // This method reads the number provided using keyboard double num = scan.nextDouble(); // Closing Scanner after the use scan.close(); // Squaring the number double square = returnSquare(num); // Displaying the Square System.out.println("The Square of the number is : " + square); } }
Output:
Enter a number: 7
The Square of the number is : 49.0
Here, the advantage of using Math.pow() function is that using it we can extend the program to find any power of the number.
Math.pow(num, 2) for square, Math.pow(num, 3) for cube, Math.pow(num, 8) for num to the power of 8.