Find area & perimeter of rectangle in java (with example)
Yogesh
Given a length and breadth of a rectangle, find the area and perimeter of rectangle.
Area of rectangle is length * breadth
e.g if length is 5 and breadth is 7, then area of rectangle is
Area = 5 * 7
Area = 35
Perimeter of rectangle is 2 * (length + breadth)
e.g if length is 5 and breadth is 7, then perimeter of rectangle is
Perimeter = 2 * (5 + 7)
Perimeter = 24
Program: calculate area & perimeter of rectangle in java
package org.learn;
import java.util.Scanner;
public class AreaAndPerimeterOfRectangle {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.printf("1. Enter length of rectangle : ");
double length = scanner.nextDouble();
System.out.printf("2. Enter breadth of rectangle : ");
double breadth = scanner.nextDouble();
//Area of rectangle is length * breadth
double area = length * breadth;
//Print area up to two precision
System.out.printf("3. Area of rectangle is : %4.2f",area);
//Perimeter of rectangle is length * breadth
double perimeter = 2 * (length + breadth);
//Print area up to two precision
System.out.printf("\n4. Perimeter of rectangle is : %4.2f",perimeter);
}
}
}
Output: area & aerimeter of rectangle using java is as follows:
1. Enter length of rectangle : 5
2. Enter breadth of rectangle : 7
3. Area of rectangle is : 35.00
4. Perimeter of rectangle is : 24.00
1. Enter length of rectangle : 10
2. Enter breadth of rectangle : 15
3. Area of rectangle is : 150.00
4. Perimeter of rectangle is : 50.00