Java Exercises: Print the area and perimeter of a rectangle
Java Basic: Exercise-13 with Solution
Write a Java program to print the area and perimeter of a rectangle.
Java: Perimeter of a rectangle
A perimeter is a path that surrounds a two-dimensional shape. The word comes from the Greek peri (around) and meter (measure). The perimeter can be used to calculate the length of fence required to surround a yard or garden. Following image represents the perimeter of a rectangle.
Java: Area of a rectangle
In Euclidean plane geometry, a rectangle is a quadrilateral with four right angles. To find the area of a rectangle, multiply the length by the width.
A rectangle with four sides of equal length is a square.
Following image represents the area of a rectangle.
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise13 {
public static void main(String[] strings) {
final double width = 5.6;
final double height = 8.5;
double perimeter = 2*(height + width);
double area = width * height;
System.out.printf("Perimeter is 2*(%.1f + %.1f) = %.2f \n", height, width, perimeter);
System.out.printf("Area is %.1f * %.1f = %.2f \n", width, height, area);
}
}
Sample Output:
Perimeter is 2*(8.5 + 5.6) = 28.20 Area is 5.6 * 8.5 = 47.60
Flowchart:

Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program that takes five numbers as input to calculate and print the average of the numbers.
Next: Write a Java program to print an American flag on the screen.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
Java: How to round a number to n decimal places in Java
Use setRoundingMode, set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output.
DecimalFormat df = new DecimalFormat("#.####"); df.setRoundingMode(RoundingMode.CEILING); for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) { Double d = n.doubleValue(); System.out.println(df.format(d)); }
Output:
12 123.1235 0.23 0.1 2341234.2125
For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:
Double d = n.doubleValue() + 1e-6;
To round down, subtract the accuracy.
Ref: https://bit.ly/3a4mvz0
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises