W Pattern with Asterick and Space Example in Java
Introduction
W pattern with Asterick and Space 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.
W Pattern Example Program
import java.util.Scanner;
class StarPatternExampleOne {
public static void main(String[] args) {
System.out.println("Enter the number of rows for pattern : ");
Scanner scanner = new Scanner(System.in);
int rowsCount = scanner.nextInt();
int spacesCount = (rowsCount * 2) - 2;
for (int i = 0; i < rowsCount; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int j = 0; j < spacesCount; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
spacesCount = spacesCount - 2;
System.out.println("");
}
}
}Sample Output
Enter the number of rows for pattern :
8
* *
** **
*** ***
**** ****
***** *****
****** ******
******* *******
****************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. -
import java.util.Scanner;imports a class used later in the program. -
A
println/printcall writes text to the console — part of the sample output below. -
A
Scannerreads typed input from the keyboard (System.in). -
int rowsCount = scanner.nextInt();updates a variable used in the calculation or output. -
int spacesCount = (rowsCount * 2) - 2;updates a variable used in the calculation or output. -
for (int i = 0; i < rowsCount; i++) {updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below.