Inverted Triangle Example in Java
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
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
*********
*******
*****
***
*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
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
for (int i= 5; i >= 1; i--) {updates a variable used in the calculation or output. -
for (int j = 0; j < 5 - i; j++){updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
for (int j = (2 - i); j < (2 - i) + (2 * i - 1); j++){updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
Compare your console output with the sample output for Inverted Triangle to confirm the program behaves correctly.