# Basic Java programming exercises

 Java Tutorial Java Exercises Data Structures

## Java program to find perimeter of a rectangle

Write a Java program to input length and width of a rectangle and calculate perimeter of the rectangle. How to find perimeter of a rectangle in Java programming. Logic to find the perimeter of a rectangle if length and width are given in Java programming.

##### Required knowledge

Operators, Data types, Defining Variables, Basic input/output

##### Perimeter of rectangle

Perimeter of rectangle is given by the below formula

2(l+w)

Where l is length and w is the width of rectangle.

##### Logic to find perimeter of a rectangle

Below is the step by step descriptive logic to find perimeter of a rectangle

1. Input length and width of the rectangle using scanf() function. Store it in two variables say length and width.

2. Calculate perimeter using formula for perimeter of rectangle perimeter = 2 * (length + width).

3. Print the value of perimeter.

##### Program to find perimeter of rectangle
```/**
* Java program to find perimeter of rectangle
*/

import java.util.Scanner;

class Test
{
public static void main(String args[])
{
float length, width, perimeter;
Scanner op=new Scanner(System.in);
/*
* Input length and width of rectangle from user
*/
System.out.print("Enter length of the rectangle: ");
length=op.nextFloat();
System.out.print("Enter width of the rectangle: ");
width=op.nextFloat();

/* Calculate perimeter of rectangle */
perimeter = 2 * (length + width);

/* Print perimeter of rectangle */
System.out.println("Perimeter of rectangle ="+perimeter+" units ");
}
}
```

##### Output:

```Enter length of the rectangle: 5
Enter width of the rectangle: 3
Perimeter of rectangle =16.0 units
```

Note: Never forget to prioritize the order of operations using a pair of braces ( ). Since, statements perimeter = 2 * length + width and perimeter = 2 * (length + width) will generate different results.