Write a Java program to Calculate area of Hexagon


This Java program calculates the area of a regular hexagon based on its side length. Here is the explanation of each point of the code:

  • import java.util.Scanner;: This line imports the Scanner class which allows the user to input values.
  • public class Area_Hexagon: This line defines a public class named "Area_Hexagon".
  • public static void main(String[] args): This line declares the main method of the program, which is executed when the program is run.
  • Scanner input = new Scanner(System.in);: This line creates a new Scanner object called "input" to read user input.
  • System.out.print("Enter the Length : ");: This line prompts the user to enter the length of the hexagon.
  • double len = input.nextDouble();: This line reads the user input and stores it in a variable called "len".
  • System.out.print("Area of the Hexagon is : " + calculate_area(len)+"\n");: This line prints the calculated area of the hexagon using the calculate_area method and concatenating it with the string "Area of the Hexagon is : ".
  • public static double calculate_area(double l) : This line defines a public static method called "calculate_area" that takes a double parameter "l" representing the length of a side of the hexagon and returns a double representing the area of the hexagon.
  • return (6*(l*l))/(4*Math.tan(Math.PI/6));: This line calculates the area of the hexagon using the formula (6*(l*l))/(4*Math.tan(Math.PI/6)) and returns the result. The formula calculates the area by multiplying the square of the length of a side by 6 and dividing it by four times the tangent of pi/6 radians, which is equivalent to the square root of 3.

Source Code

import java.util.Scanner;
public class Area_Hexagon 
{
	public static void main(String[] args) 
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the Length : ");
		double len = input.nextDouble();
		System.out.print("Area of the Hexagon is : " + calculate_area(len)+"\n");
	}
 
	public static double calculate_area(double l)
	{
		return (6*(l*l))/(4*Math.tan(Math.PI/6));
	}
}

Output

Enter the Length : 53
Area of the Hexagon is : 7297.996077691465

Example Programs