Java Programs

Java Program to calculate square of number

In this tutorial, we will learn writing Java program to calculate the square of a given number. Our program will take a number as an input and will return the square of that number as output.

What is Square of Number?

When a number is multiplied to itself once, resultant number is known as square of number.

For example:

Suppose we want to calculate the square of 5.

Square of 5 = 5^2 = 5*5 = 25.

Program to calculate square of number in Java

import java.util.*;

public class Main {
	
    public static void main(String[] args) {
    	
        float num,square;
        Scanner sc = new Scanner(System.in);
        System.out.println("Please give the number to calculate square");
        num= sc.nextFloat();
        square = num*num;
        System.out.println("Square of "+num+" is ");
        System.out.printf("%.2f", square);
    }
}

Output:

Please give the number to calculate square
5
Square of 5.0 is 
25.00

Explanation

For input 5, the output generated by our program is 5.0*%.0 i.e. equals 25.0.

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs