Java Program to Calculate the Area of a Triangle
A triangle is a shape with three sides and three corners. Its area can be calculated in two common ways:
- from the base and height:
area = (base × height) / 2, - from the three sides
a,bandc, using Heron's formula:area = √(s(s - a)(s - b)(s - c)), wheres = (a + b + c) / 2is half the perimeter.
1. Area from Base and Height
The height is the perpendicular distance from the base to the opposite corner.
public class TriangleArea {
public static void main(String[] args) {
double base = 21.75;
double height = 10.5;
double area = (base * height) / 2;
System.out.println("Base: " + base);
System.out.println("Height: " + height);
System.out.println("Area of the triangle: " + area);
}
}
Output
Base: 21.75 Height: 10.5 Area of the triangle: 114.1875
2. Area from Base and Height with User Input
import java.util.Scanner;
public class TriangleAreaInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base: ");
double base = scanner.nextDouble();
System.out.print("Enter the height: ");
double height = scanner.nextDouble();
scanner.close();
if (base <= 0 || height <= 0) {
System.out.println("Base and height must be positive.");
return;
}
System.out.printf("Area of the triangle: %.2f%n", 0.5 * base * height);
}
}
Output (with sample input)
Enter the base: 30.5 Enter the height: 20.75 Area of the triangle: 316.44
3. Area from Three Sides Using Heron's Formula
Three lengths only form a triangle if each side is shorter than the sum of the other two (the triangle inequality). The program checks this first, then applies Heron's formula with Math.sqrt().
public class TriangleAreaHeron {
static double area(double a, double b, double c) {
if (a + b <= c || a + c <= b || b + c <= a) {
return -1; // not a valid triangle
}
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
public static void main(String[] args) {
double[][] triangles = {{3, 4, 5}, {7, 8, 9}, {1, 2, 10}};
for (double[] t : triangles) {
double area = area(t[0], t[1], t[2]);
if (area < 0) {
System.out.println("Sides " + t[0] + ", " + t[1] + ", " + t[2] + " do not form a triangle.");
} else {
System.out.printf("Sides %.1f, %.1f, %.1f -> area %.2f%n", t[0], t[1], t[2], area);
}
}
}
}
Output
Sides 3.0, 4.0, 5.0 -> area 6.00 Sides 7.0, 8.0, 9.0 -> area 26.83 Sides 1.0, 2.0, 10.0 do not form a triangle.
4. Summary
- With base and height, the area is
base * height / 2. - With three sides, use Heron's formula:
Math.sqrt(s * (s - a) * (s - b) * (s - c))withsas half the perimeter. - Check the triangle inequality before using Heron's formula.
- Use
doublefor lengths andprintf("%.2f")to format the result.
Related Programs
Was this tutorial helpful?