Nested Loop Word Triangles (BLUEJ Pattern) in Java

⚡ Direct Answer & Key Takeaway

Nested-loop word patterns such as the BLUEJ triangle print progressive prefixes of a String using word.length() and word.charAt(j). An outer loop controls row index i from 0 to len - 1, while an inner loop prints characters from index j = 0 up to i, ending each row with System.out.println(). Converting input via toUpperCase() guarantees consistent uppercase board output regardless of how the user types the word.

1. Mapping Outer Row Loops to String Index Bounds

Java strings are zero-indexed, meaning the characters of "BLUEJ" reside at positions 0 ('B'), 1 ('L'), 2 ('U'), 3 ('E'), and 4 ('J'), while word.length() returns 5. In a nested-loop triangle, the outer loop variable i selects which row is currently being built, running strictly from 0 to len - 1 (written i < len). For each row i, the inner loop variable j runs from 0 up to and including i (written j <= i). Because row 0 ends at index 0, it prints 1 letter; row 1 prints indices 0 and 1; and row 4 prints indices 0 through 4. Separating System.out.print inside the inner loop from System.out.println after the inner loop keeps each row's letters together horizontally before dropping to the next line.

  • Zero-based indices run from 0 to word.length() - 1; hitting index len throws StringIndexOutOfBoundsException.
  • Outer loop i governs row count (5 rows for "BLUEJ"), while inner loop j <= i governs columns per row.
  • Place System.out.println() strictly outside the inner loop so newlines happen once per row.

2. Row-by-Row Dry Run Trace for the Word BLUEJ

Trace word = "BLUEJ", where len = 5. At row i = 0, j runs only for 0: ch = 'B', prints "B ", then println moves to line 2. At row i = 1, j runs for 0 and 1: prints "B ", then "L ", then println drops to line 3. At row i = 2, j runs for 0, 1, 2: prints "B L U ", then newline. At row i = 3, j runs for 0, 1, 2, 3: prints "B L U E ", then newline. Finally, at row i = 4, j runs for 0, 1, 2, 3, 4: prints "B L U E J ", then newline. When i increments to 5, 5 < 5 is false, ending the outer loop cleanly.

  • Row i = 0 -> j = 0 -> outputs B.
  • Row i = 2 -> j = 0, 1, 2 -> outputs B L U.
  • Row i = 4 -> j = 0, 1, 2, 3, 4 -> outputs B L U E J, then outer loop finishes.

3. Using charAt Versus substring in ICSE Pattern Questions

ICSE examiners love testing slight variations of word patterns, such as printing "B", "LL", "UUU", "EEEE", "JJJJJ" (where the inner loop prints word.charAt(i) instead of word.charAt(j)) or printing without spaces between letters. When no spaces are required between letters, a single loop calling System.out.println(word.substring(0, i + 1)) achieves the identical triangle concisely because substring(start, end) excludes end. However, whenever a question shows spaces between characters or prints repeated letters per row, a nested charAt loop gives full control over spacing. Notice also how .trim().toUpperCase() protects against accidental leading spaces or lowercase user input in BlueJ terminal runs.

  • Printing word.charAt(j) outputs prefixes (B, B L, B L U); printing word.charAt(i) outputs repeated letters (B, L L, U U U).
  • Remember substring(0, i + 1) upper bound is exclusive, so i + 1 never throws an error when i < len.
  • If the exam asks for a rectangle instead of a triangle, change j <= i to j < len.

4. WordTrianglePattern.java

import java.util.Scanner;

public class WordTrianglePattern {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word (e.g., BLUEJ): ");
        String word = sc.next().trim().toUpperCase();

        int len = word.length();
        if (len == 0) {
            System.out.println("Word cannot be empty.");
            sc.close();
            return;
        }

        for (int i = 0; i < len; i++) {
            for (int j = 0; j <= i; j++) {
                char ch = word.charAt(j);
                System.out.print(ch + " ");
            }
            System.out.println();
        }

        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter a word (e.g., BLUEJ): BLUEJ
B 
B L 
B L U 
B L U E 
B L U E J

5. Variable Description Table (VDT) — WordTrianglePattern

Variable NameData TypePurpose in Program
scScannerReads the input word from the BlueJ console
wordStringStores the trimmed uppercase word used for the triangle pattern
lenintStores word.length(), controlling the number of rows
iintOuter loop counter representing the current row index (0 to len - 1)
jintInner loop counter selecting character positions from 0 to i
chcharStores the character word.charAt(j) printed in the inner loop
🎯 1-on-1 Live Mentorship & Free Study Kit

Solve ICSE Pattern & String Questions with Free 1:1 Practice

Master nested-loop patterns and String indexing for ICSE Class 10 Computer Applications with 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods).

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Running the inner loop condition as j < len instead of j <= i, which prints a solid rectangle of BLUEJ on every row instead of a triangle.
  • Avoid Mistake: Using i <= len instead of i < len, causing StringIndexOutOfBoundsException at charAt(len).
  • Avoid Mistake: Calling System.out.println(ch) inside the inner loop instead of System.out.print(ch), printing every letter on its own separate line.
  • Avoid Mistake: Indexing characters starting at 1 instead of 0, skipping the first letter 'B' and crashing at the end of the string.
  • Examiner / Mentor Tip: Always check whether the pattern in the exam paper has spaces between characters before choosing charAt + " " vs substring.
  • Examiner / Mentor Tip: Remember that length() is a method on String (needs parentheses), whereas length on arrays is a field (no parentheses).
  • Examiner / Mentor Tip: Know how to reverse the outer loop (for i = len - 1; i >= 0; i--) for inverted triangle follow-up questions in viva.

7. Interactive Concept Check Quiz

Question: If the word entered is "JAVA", how many total characters (excluding spaces and newlines) are printed by the nested loop for (int i = 0; i < len; i++) for (int j = 0; j <= i; j++)?

8. Frequently Asked Questions

How do I invert the triangle so BLUEJ appears on the top row and B on the bottom?
Outer loop runs from i = len - 1 down to 0, while the inner loop still runs from j = 0 up to i. That reverses the row lengths to print BLUEJ, BLUE, BLU, BL, B.
Should I use sc.next() or sc.nextLine() for word pattern inputs?
Use sc.next() for a single word without spaces (like BLUEJ), or sc.nextLine() if the question asks for a multi-word phrase.
Can word.substring(0, i + 1) replace the inner loop?
Yes, System.out.println(word.substring(0, i + 1)) prints compact rows without spaces; nested charAt loops are needed when spaces are placed between letters like B L U E J.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class