How to Square a Number in Java
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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: …