ThisCalculator

Everyday

Area of Triangle in Java: 3 Ways With Code

Updated · Standard formula, shown below

Area (base × height / 2) 25.00 m²
Area via Heron (if sides known)
Cannot compute m²
Result
Base length
10 m
You entered
Height
5 m
You entered

Area of Triangle in Java: 3 Ways With Code

To find the area of a triangle in Java, you use the formula area = (base * height) / 2 for the base-height method, or area = sqrt(s * (s - a) * (s - b) * (s - c)) (Heron’s formula) when you know all three side lengths. This article shows you both formulas in working Java code, explains how to handle user input, and points out the common pitfalls that produce wrong results.

Formula

For a triangle with a known base and height:

Area = (base × height) / 2

  • base – length of one side of the triangle (in any unit, e.g., m, cm, ft)
  • height – perpendicular distance from the base to the opposite vertex (same unit as base)

For a triangle where you know all three sides (a, b, c), use Heron’s formula:

Area = √(s × (s − a) × (s − b) × (s − c))

  • a, b, c – side lengths (same unit)
  • s – semiperimeter = (a + b + c) / 2

Worked Example

Using the default values from the calculator above: base = 10 m, height = 5 m.

  1. Multiply base by height: 10 × 5 = 50
  2. Divide by 2: 50 / 2 = 25
  3. Area = 25 m²

The calculator also shows a Heron’s formula example using the same two numbers as legs of a right triangle (the third side is √(10² + 5²) ≈ 11.18 m). The semiperimeter s = (10 + 5 + 11.18) / 2 = 13.09. Heron’s formula gives √(13.09 × (13.09 − 10) × (13.09 − 5) × (13.09 − 11.18)) ≈ 25.00 m², matching the base-height result because both describe the same right triangle.

Java Code: Base × Height Method

The simplest Java program reads the base and height, computes the area, and prints it. Here’s a complete example using the Scanner class:

import java.util.Scanner;

public class TriangleArea {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter base: ");
        double base = sc.nextDouble();
        System.out.print("Enter height: ");
        double height = sc.nextDouble();
        double area = (base * height) / 2;
        System.out.println("Area = " + area);
        sc.close();
    }
}

Note that (base * height) / 2 is written with parentheses. If you write base * height / 2, Java evaluates it left-to-right, which is fine because multiplication and division have the same precedence. However, using the parentheses makes the intent clear and avoids mistakes if you later modify the formula.

Java Code: Heron’s Formula (Three Sides)

When you only know the side lengths, use Heron’s formula. The Math.sqrt() method gives the square root:

import java.util.Scanner;

public class HeronArea {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter side a: ");
        double a = sc.nextDouble();
        System.out.print("Enter side b: ");
        double b = sc.nextDouble();
        System.out.print("Enter side c: ");
        double c = sc.nextDouble();
        double s = (a + b + c) / 2;
        double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
        System.out.println("Area = " + area);
        sc.close();
    }
}

Heron’s formula only works for a valid triangle: the sum of any two sides must be greater than the third side. If you enter sides like 1, 2, 3, the value inside the square root becomes negative and Math.sqrt() returns NaN (Not a Number). In a real program, you should check the triangle inequality before computing.

How to Choose the Right Method

Your choice depends on what data you have:

  • Base and height available – use the simple formula. It’s faster and less error-prone.
  • Only three sides known – use Heron’s formula.
  • Two sides and the included angle known – use area = 0.5 * a * b * sin(angle) (angle in radians for Math.sin()).
  • Coordinates of vertices known – use the shoelace formula: area = 0.5 * |x1(y2 - y3) + x2(y3 - y1) + x3(y1 - y2)|.

For most beginner exercises, base×height is the expected solution. Heron’s formula appears when the problem gives three sides but no height.

Common Mistakes and Pitfalls

Several errors frequently produce wrong results:

  • Integer division – If base and height are declared as int, then (base * height) / 2 performs integer division. For base=5, height=3, you get 15/2 = 7 (not 7.5). Always use double for measurements.
  • Using the wrong height – The height must be perpendicular to the base, not just any side length. In a scalene triangle, the height is not the same as a side.
  • Forgetting the square root – In Heron’s formula, forgetting Math.sqrt() leaves you with the square of the area.
  • Not validating input – Negative base or height gives a negative area, which is meaningless. Sides that violate the triangle inequality produce NaN.
  • Unit confusion – If base is in meters and height in centimeters, you must convert one to the other before multiplying. The area unit is the square of whatever unit you use.

Handling User Input and Edge Cases

In real applications, you should validate input. Use Scanner.hasNextDouble() to check if the user entered a number, and reject non-positive values. For example:

if (base <= 0 || height <= 0) {
    System.out.println("Base and height must be positive.");
} else {
    double area = (base * height) / 2;
    // ...
}

For Heron's formula, add a check like if (a + b > c && a + c > b && b + c > a) before computing. Also be aware that floating-point rounding can cause tiny errors (e.g., 0.1 + 0.2 != 0.3 exactly), but for typical triangle areas this is negligible.

Limitations of the Formulas

Both formulas work for any triangle in Euclidean geometry. However, they assume a flat plane. On a sphere (like Earth), you'd need spherical trigonometry. Also, if you have very large numbers, the intermediate product (base × height) might overflow a double (max about 1.8 × 10^308). For most practical purposes, this is not an issue. Heron's formula can suffer from numerical instability for very skinny triangles (one side much smaller than the others), but for typical inputs it's fine.

Frequently Asked Questions

Why does my Java program give 0 for the area?

Most likely you used integer division. If base and height are int variables and you write area = base * height / 2, Java does integer arithmetic and truncates the decimal. For example, 5 * 3 / 2 = 7, not 7.5. Declare the variables as double or cast one to double before dividing.

Can I use Heron's formula with any three numbers?

No. The three numbers must form a valid triangle: the sum of any two sides must be greater than the third. If not, the formula gives a negative number under the square root, and Math.sqrt() returns NaN. Always check the triangle inequality first.

How do I get the result with only two decimal places?

Use System.out.printf("%.2f", area) or String.format("%.2f", area). This rounds the output for display without changing the stored value.

What if I know the coordinates of the vertices?

Use the shoelace formula: area = 0.5 * Math.abs(x1*(y2 - y3) + x2*(y3 - y1) + x3*(y1 - y2)). This works for any triangle and avoids needing the height.

Is there a built-in Java method for triangle area?

No, Java's standard library does not include a geometric area method. You must implement the formula yourself.

What is the output type of Math.sqrt()?

It returns a double. If you need a float, cast it: (float) Math.sqrt(...). For most applications, double is the right choice.

Related

Formula used
in base | Base length | m | 10 | 0
in height | Height | m | 5 | 0
out area | Area (base × height / 2) | m² | base * height / 2 | 2
out area_heron | Area via Heron (if sides known) | m² | sqrt((base/2 + height/2 + sqrt(base*base + height*height)) / 2 * ((base/2 + height/2 + sqrt(base*base + height*height)) / 2 - base/2) * ((base/2 + height/2 + sqrt(base*base + height*height)) / 2 - height/2) * ((base/2 + height/2 + sqrt(base*base + height*height)) / 2 - sqrt(base*base + height*height))) | 2

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.