Java Program to Calculate Area of Rectangle
Overview
In this post, we will write a java program to calculate the area of the rectangle and perimeter of the Rectangle. We will have two java classes.
- Rectangle class
- RectangleMain driver class
Eclipse IDE Setup
Some steps and instructions to create a Java application on Eclipse IDE:
- Create Java Project in Eclipse
https://www.testingdocs.com/create-a-new-java-project-in-eclipse/
- Create Java Package in Eclipse
https://www.testingdocs.com/create-java-package-in-eclipse-ide/
- Create Java Class in Eclipse
https://www.testingdocs.com/create-a-new-java-class-in-a-project/
- Run Java Project in Eclipse
https://www.testingdocs.com/run-java-project-in-eclipse/
Java Program
Rectangle class
/************************************************** * Rectangle.java class * @program : * @web : www.TestingDocs.com * @author : * @version : 1.0 **************************************************/ public class Rectangle { private double height; private double width; /** * @param height * @param width */ public Rectangle(double height, double width) { this.height = height; this.width = width; } /** * @return the height */ public double getHeight() { return height; } /** * @param height the height to set */ public void setHeight(double height) { this.height = height; } /** * @return the width */ public double getWidth() { return width; } /** * @param width the width to set */ public void setWidth(double width) { this.width = width; } //calculating Area of the rectangle public double calculateArea() { return width * height; } //calculating perimeter of the rectangle public double calculatePerimeter() { return 2*(width + height); } }
RectangleMain
/************************************************** * RectangleMain.java * @program : Demo program of Rectangle class * @web : www.TestingDocs.com * @author : * @version : 1.0 **************************************************/ public class RectangleMain { public static void main(String args[]) { // Creating Rectangle object Rectangle r1 = new Rectangle(5.0,3.5); System.out.println("--------------Output----------"); System.out.println("Height of r1 in centimeter = " + r1.getHeight()); System.out.println("Width of r1 in centimeter = " + r1.getWidth()); System.out.println("Area of r1 = " + r1.calculateArea() + " cm ^2"); System.out.println("Perimeter of r1 = " + r1.calculatePerimeter() + " cm"); } }
Output
————–Output———-
Height of r1 in centimeter = 5.0
Width of r1 in centimeter = 3.5
Area of r1 = 17.5 cm ^2
Perimeter of r1 = 17.0 cm
Screenshot
—
Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :