How to get the area of a Hexagon in Java
A regular hexagon is a six-sided polygon that has equal-length sides and 120–degree interior angles.
Formula for the area of a hexagon
When calculating the area of a regular hexagon, apply the following formula:
Where length in the above formula represents the length of a side of a hexagon.
Problem statement
We are given a length of a hexagon, and we have to calculate its area using the formula above.
Explanation
Let’s suppose we have a length of 7. When we put the value of the length in the above formula, we have have the following equation:
Implementation
The approach here is to use the sqrt function for calculating the sqrt(3). For that, we use java.lang.Math package. We’ll declare the values of type double because the length can be in decimal form or may vary.
Let’s see an example to calculate the area of a hexagon:
import java.lang.Math;class Area {public static void main( String args[] ) {double length = 7.0;double area = 0.0; // Variable to calculate the area of a hexagonarea = (3 * Math.sqrt(3) * length * length) / 2;System.out.println("Area of a hexagon with length " + length + " is: " + area );}}
Explanation
- Line 1: We use the
java.lang.Mathpackage so we can use thesqrtfunction in the code. - Line 5: We declare a variable,
length, to store the length of a hexagon. - Line 6: We declare a variable,
area, to store the value of the area. - Line 8: We use the formula to calculate the area of the hexagon.
- Line 9: Then, we display the area of the hexagon.
Free Resources