Java Program to Find the Square of a Number

Learn how to find the square of a number in Java using the Scanner class, user input, and a simple multiplication operation . Squaring a number is one of the most basic mathematical operations in Java.

Code Explanation (Step-by-Step)

  • Create a Scanner class object to accept user input.
  • Use the sc.nextInt() method to read an integer value.
  • Create a square() method that accepts a number as a parameter.
  • Multiply the number by itself (n * n) to find its square.
  • Now print the Square of a Number.
				
					import java.util.Scanner;

public class SquareNumber {

    int square(int n) {
        return n * n;
    }

    public static void main(String[] args) {

        SquareNumber sn = new SquareNumber();
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number value: ");
        int n = sc.nextInt();

        System.out.println("The square of a number is: " + sn.square(n));

        sc.close();
    }
}
				
			

Output :-
enter the number value :
12
The square of a number is :- 144

How to Square a Number in Java

				
					import java.util.Scanner;

public class SquareNumber {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number value: ");
        int n = sc.nextInt();

        double square = Math.pow(n, 2);

        System.out.println("The square of a number is: " + (int) square);

        sc.close();
    }
}