Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Star Patterns in Java

Draw a growing star triangle in Java with nested loops and System.out.print. Row five contains five stars; println after each inner loop keeps the shape.

BeginnerJava Loop ProgramsExample 16 of 25
star-patterns.java
1public class Main {
2 public static void main(String[] args) {
3 int n = 5;
4 for (int i = 1; i <= n; i++) {
5 for (int j = 1; j <= i; j++) {
6 System.out.print("*");
7 }
8 System.out.println();
9 }
10 }
11}

Sample Output

*
**
***
****
*****

The row lengths are 1, 2, 3, 4, and 5. There are no spaces between stars in this version.

In this one

  • Repeat a symbol a chosen number of times
  • Separate counting from printed content
  • End a row after inner-loop completion

How it works

  1. 1

    Set n to 5.

  2. 2

    Start a row with i.

  3. 3

    Print a star for j = 1 through i.

  4. 4

    Move to a new line and advance the row.

Edge cases

Single star

Set n = 1

One star and a newline print.

Extra spaces

Change print("*") to print("* ")

The rows still have the same number of stars but become wider because of the spaces.

What's going on

Draw a right triangle using stars. The first row contains one star and each later row contains one more. This is useful for practising repeated output before trying patterns that need spaces or several kinds of symbols.

The code uses a nested loop, which means one loop inside another. The outer loop chooses row i from 1 to 5. The inner loop runs i times and prints a star on each pass. System.out.print keeps the stars together, while println ends the completed row.

At row 4 the inner loop prints four stars, not the number four. The j counter decides how many times printing happens, but is not itself displayed. Putting println inside the inner loop would make a vertical column instead of rows. Changing the printed symbol can create the same shape with hashes or other characters.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

How many stars appear in row 3?

Pick an answer to check it.

Question 2

Which call ends a row?

Pick an answer to check it.

Questions people ask

Why is j not shown?

It is only a counter. The print call contains a fixed star instead of j.

How many stars print in total for five rows?

15: 1 + 2 + 3 + 4 + 5.

Can I use a different character?

Yes. Replace the star string while keeping the loop counts the same.