Calculate Area of Triangle in Java
beginner· Basics & I/O · Geometry
Problem
A triangle's area is half its base times its height — a triangle is effectively half of the rectangle that would enclose it.
Given the base and height of a triangle, calculate its area.
Input
base = 10.0, height = 6.0
Output
Area: 30.0
Java Program
Java
public class CalculateAreaOfTriangle {
public static void main(String[] args) {
double base = 10.0;
double height = 6.0;
double area = 0.5 * base * height; // half of base times height
System.out.println("Area: " + area);
}
}Output
Area: 30.0
Core Logic
Multiplying base by height and halving the result gives the area directly, in a single expression.
How It Works
- 1
baseholds10.0andheightholds6.0. - 2
0.5 * base * heightevaluates to30.0. - 3The result is stored in
areaand printed with a label.
For
base = 10.0 and height = 6.0, 0.5 * 10.0 * 6.0 gives 30.0.💡
Key Point: Writing 0.5 * instead of / 2 avoids any risk of accidental integer division if the base and height were ever declared as int instead of double.
Key Concepts
doublearithmetic expression
Approach 2: Java 8
Java
import java.util.function.DoubleBinaryOperator;
public class CalculateAreaOfTriangleLambda {
public static void main(String[] args) {
double base = 10.0;
double height = 6.0;
// The area formula is stored as a lambda, named for what it computes
DoubleBinaryOperator areaOf = (b, h) -> 0.5 * b * h;
double area = areaOf.applyAsDouble(base, height);
System.out.println("Area: " + area);
}
}
Output
Area: 30.0
Core Logic
The area formula can be wrapped in a named lambda, turning 'compute a triangle's area' into a small reusable function.
How It Works
- 1
DoubleBinaryOperator areaOf = (b, h) -> 0.5 * b * h;stores the formula as a lambda. - 2
areaOf.applyAsDouble(base, height)calls it, returning the same result the inline expression would. - 3The result is printed exactly as before.
With
base = 10.0 and height = 6.0, areaOf.applyAsDouble(10.0, 6.0) returns 30.0.💡
Key Point: Storing the formula as areaOf makes it trivial to reuse for many triangles, instead of retyping 0.5 * base * height at every call site.
Key Concepts
DoubleBinaryOperatorfunctional interfacelambda expression