Java Program to find area of square
In this program let us create a Java program to print the area of square.
Program
import java.util.Scanner;
public class AreaofSquare {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the length:\t");
int length = sc.nextInt();
int area = length * length;
System.out.println("Area of square is:\t" + area);
}
}
Let us understand the program by breaking into simple parts:
public class AreaofSquare
: Any Java program starts with a class, in this case the class name is AreaofSquarepublic static void main(String[] args)
: main is the entry point for any Java program.Scanner sc = new Scanner(System.in);
: System.in is passed as a parameter in Scanner class. This creates an object of Scanner class which is defined in java. util. scanner package. Scanner class tells the java compiler that system input will be provided through console(keyboard). System.in corresponds to keyboard input or another input source specified by the host environment or user.int length = sc.nextInt();
: The nextInt() method of Java Scanner class is used to scan the next token of the input as an int. The value of length entered by the user is stored in the variable length.int area = length * length;
: Calculate the area of squareSystem.out.println("Area of square is:\t" + area);
: System.out.println prints the area of square with user entered inputs.
Output
Enter the length: 13
Area of square is: 169