Java program to calculate area of Square

Java program to calculate area of Square


In this tutorial we will learn how to calculate area of Square. Following are the two ways to do it:
1) Program 1: Prompting user for entering the side of the square
2) Program 2: Side of the square is specified in the program’ s source code.
Program 1:
/**
* @author: BeginnersBook.com
* @description: Program to Calculate Area of square.Program
* will prompt user for entering the side of the square.
*/

import java.util.Scanner;
class SquareAreaDemo {
public static void main (String[] args)
{
System.out.println("Enter Side of Square:");
//Capture the user's input
Scanner scanner = new Scanner(System.in);
//Storing the captured value in a variable
double side = scanner.nextDouble();
//Area of Square = side*side
double area = side*side;
System.out.println("Area of Square is: "+area);
}
}
Output:
Enter Side of Square:
2.5
Area of Square is: 6.25
Program 2:
/**
* @author: BeginnersBook.com
* @description: Program to Calculate Area of square.
* No user interaction: Side of square is hard-coded in the
* program itself.
*/

class SquareAreaDemo2 {
public static void main (String[] args)
{
//Value specified in the program itself
double side = 4.5;
//Area of Square = side*side
double area = side*side;
System.out.println("Area of Square is: "+area);
}
}
Output:
Area of Square is: 20.25

Post a Comment

Previous Post Next Post