Skip to main content
Browse topics

Inverted Triangle Example in Java

2 min read Updated May 29, 2026
Share

Introduction

Inverted Triangle is a classic Java console program that demonstrates the concept with complete source code and sample output. Pattern programs print shapes with nested loops — common in exams and interviews.

This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.

Inverted Triangle Example Program

java
public class InvertedTriangle{
    public static void main(String args[]) {
        for (int i= 5; i >= 1; i--) { 
            for (int j = 0; j < 5 - i; j++){
                System.out.print(' ');
			}
            for (int j = (2 - i); j < (2 - i) + (2 * i - 1); j++){
                System.out.print('*');
			}
            System.out.print('\n');
        }
	}
}

Sample Output

plaintext
*********
 *******
  *****
   ***
    *

When to use

Use pattern logic when practicing nested loops or preparing for coding tests that ask for triangle or pyramid output.

How it works

  1. Execution begins in the main method — the JVM calls this method when you run the class.

  2. for (int i= 5; i >= 1; i--) { updates a variable used in the calculation or output.

  3. for (int j = 0; j < 5 - i; j++){ updates a variable used in the calculation or output.

  4. A println / print call writes text to the console — part of the sample output below.

  5. for (int j = (2 - i); j < (2 - i) + (2 * i - 1); j++){ updates a variable used in the calculation or output.

  6. A println / print call writes text to the console — part of the sample output below.

  7. A println / print call writes text to the console — part of the sample output below.

  8. Compare your console output with the sample output for Inverted Triangle to confirm the program behaves correctly.

Best Practices

Common Mistakes

Frequently Asked Questions

What does the Inverted Triangle program demonstrate?
It shows how to implement inverted triangle in Java with a complete runnable example and expected console output.
How do I run this Java program?
Save the code in a `.java` file matching the public class name, compile with `javac`, then run with `java ClassName`.
When would I use this pattern?
Use pattern logic when practicing nested loops or preparing for coding tests that ask for triangle or pyramid output.

Related tutorials

Search tutorials