Java ProgramsControl FlowCheck Valid Triangle

Check Valid Triangle in Java

beginner·  Control Flow  ·  Conditional Statements

Problem

The triangle inequality theorem says a triangle can only exist when the sum of any two sides is strictly greater than the third.

Given three side lengths, determine whether they can form a valid triangle.

Input
a = 7, b = 10, c = 5
Output
Valid triangle: true

Java Program

Java
public class ValidTriangle { public static void main(String[] args) { int a = 7, b = 10, c = 5; boolean isValid = (a + b > c) && (b + c > a) && (a + c > b); // all three pairwise checks must hold System.out.println("Valid triangle: " + isValid); } }

Output

Valid triangle: true

Core Logic

Checking all three pairwise sums against the remaining side confirms the triangle inequality holds in every direction, not just one.

How It Works
  1. 1a + b > c checks the inequality for the first pair against the third side.
  2. 2b + c > a and a + c > b check the remaining two pairs the same way.
  3. 3&& combines all three checks — the sides form a valid triangle only if none of them fail.
For 7, 10, 5: 7+10=17>5, 10+5=15>7, and 7+5=12>10 — all three hold, so the triangle is valid.
💡

Key Point: All three pairwise checks are necessary — checking only one or two could pass a set of sides that fails the inequality on the pair you didn't check.

Key Concepts

triangle inequalitylogical ANDboolean expression

Related Programs