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:

Area=3×3×length22\text{Area} = \frac{3 \times \sqrt3 \times \text{length}^2}{2}

Where length in the above formula represents the length of a side of a hexagon.

A regular hexagon
A regular 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:

Area=3×3×length22=3×3×722=3×3×492127.31\begin{split} \text{Area} & = \frac{3 \times \sqrt3 \times \text{length}^2}{2} \\ & = \frac{3 \times \sqrt3 \times 7^2}{2} \\ & = \frac{3 \times \sqrt3 \times 49}{2} \\ & \approx 127.31 \end{split}

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 hexagon
area = (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.Math package so we can use the sqrt function 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

Copyright ©2025 Educative, Inc. All rights reserved