Java Program to Find Area Of Triangle Heron's Formulae

  • Write a program in Java to find the area of a triangle using heron's formulae.

Given the length of three sides of a triangle, we have to write a java program to find the area of given triangle. Given triangle can be either equilateral, isosceles, right angles triangle or scalene triangle.
Here we are going to calculate the area of triangle using Heron's Formula. Given length of three sides of a triangle, Heron's formula can be used to calculate the area of any triangle.

Heron's formula(also known as Hero's formula) is named after Hero of Alexandria a Greek Engineer and Mathematician.
Heron's Formulae
Let X, Y and Z be the length of three sides of a triangle.
  • Calculate the semi perimeter of the triangle as
    Semi-Perimeter of triangle(S) = (X + Y + Z)/2
  • Now, the area of triangle can be calculated as
    Area of Triangle = √ S(S-A)(S-B)(S-C))

Let the length of three sides of triangle are 5, 10 and 7 meters. As per Heron's formulae, first of all we have to calculate it's semi-perimeter.
Semi-Perimeter(S) = (5+10+7)/2 = 11
Now, we can calculate area of triangle as
Area = √ 11(11-5)(11-10)(11-7)) = √ 264 = 16.24 m2


Java Program to Find Area of a Triangle

In this java program, we first take three integer input from user as the length of three sides of a triangle and store them in s1, s2 and s3 double variable. Then we calculate the area of given triangle using heron's formulae as mentioned above.

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to find area of triangle
 */
public class AreaOfTriangle {

    public static void main(String[] args) {
        double s1, s2, s3, area, S;
        Scanner scanner;
        scanner = new Scanner(System.in);
        // Take input from user
        System.out.println("Enter Three Sides of a Triangle");
        s1 = scanner.nextDouble();
        s2 = scanner.nextDouble();
        s3 = scanner.nextDouble();

        /*
         * Area of any triangle = sqrt(s*(s-sideOne)*(s-sideTwo)*(s-sideThree))
         * Where s = (sideOne + sideTwo + sideThree)/2
         */
        S = (s1 + s2 + s3) / 2;
        area = Math.sqrt(S * (S - s1) * (S - s2) * (S - s3));

        System.out.format("The Area of triangle = %.2f\n", area);
    }
}
Output
Enter Three Sides of a Triangle
7 3 9
The Area of triangle = 8.79
Enter Three Sides of a Triangle
3 4 5
The Area of triangle = 6.00