Java ProgramsControl FlowCheck Triangle Type

Check Triangle Type in Java

intermediate·  Control Flow  ·  Conditional Statements

Problem

A triangle is classified by how many of its three sides are equal in length — three, two, or none.

Given the lengths of a triangle's three sides, classify it as equilateral, isosceles, or scalene.

Input
a = 5, b = 5, c = 8
Output
Triangle type: Isosceles

Java Program

Java
public class TriangleType { public static void main(String[] args) { int a = 5, b = 5, c = 8; String type; if (a == b && b == c) { // must be checked before Isosceles, since equal sides satisfy that too type = "Equilateral"; } else if (a == b || b == c || a == c) { type = "Isosceles"; } else { type = "Scalene"; } System.out.println("Triangle type: " + type); } }

Output

Triangle type: Isosceles

Core Logic

Checking for three equal sides first, then any two, and falling back to 'no matches' covers every classification in strict order.

How It Works
  1. 1a == b && b == c checks whether all three sides are equal, the Equilateral case.
  2. 2If that fails, a == b || b == c || a == c checks whether any single pair matches, the Isosceles case.
  3. 3If neither matched, no two sides are equal, so the triangle is Scalene.
For 5, 5, 8, the first check fails since 8 doesn't match, but a == b is true, so the triangle is classified Isosceles.
💡

Key Point: Checking the Equilateral case first matters — three equal sides would also satisfy the Isosceles condition's ||, so a stricter check has to run before the looser one.

Key Concepts

if / else iflogical ORequality comparison

Related Programs