Start learning free

LESSON 2 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v2 in Java: Number Lines with String.format

Practice Read the full explanation

Now build the -n flag of the cat tool, as a new function. It prints every line preceded by its 1-based line number, right-aligned in 6 columns, then a tab character, then the line text. Blank lines are numbered too, and an empty list gives an empty string.

Function signature:

public String numberedCat(List<String> lines)

Format per line: the line number right-aligned in a field 6 characters wide (padded with spaces on the left), then a literal tab (\t), then the original line.

Example:

Input: lines = ["hello", "world", "foo"]

Output:
"     1\thello\n     2\tworld\n     3\tfoo"

When printed:
     1	hello
     2	world
     3	foo

Use a StringBuilder to accumulate the output. Iterate by index, append a "\n" before every line except the first, then append the formatted line.

Use String.format("%6d\t%s", i + 1, lines.get(i)) to format each entry. %6d right-justifies the number in a 6-character field.

The full solution:
class Solution {
    public String numberedCat(List<String> lines) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.size(); i++) {
            if (i > 0) sb.append("\n");
            sb.append(String.format("%6d\t%s", i + 1, lines.get(i)));
        }
        return sb.toString();
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in Java, explained

    Problem overview

    The second version of the cat tool adds the -n flag as a new method, numberedCat(List<String> lines). Each line is printed with its 1-based line number first. The number is right-aligned in a field 6 characters wide, followed by a tab character and then the line's text. Blank lines are numbered too, and an empty list gives an empty string. The rows are joined with \n, with no newline after the last one.

    For ["hello", "world", "foo"] the result is the string " 1\thello\n 2\tworld\n 3\tfoo", which prints as:

         1	hello
         2	world
         3	foo
    

    Version 1 joined plain lines with String.join; this version has to change each line before joining, so it uses a loop.

    Approach: build each row, separate with newlines

    Each row depends on two things: the line's text and its position in the list. That calls for a loop over indices rather than over the lines themselves, because the index gives the line number (as i + 1, since the loop counts from 0).

    The rows go into a StringBuilder. Appending to a StringBuilder changes one buffer, while += on a String creates a new string every time. The newline between rows follows the rule from the previous version: it goes between two rows, so the first row gets none in front of it, and the last row gets none after it.

    For the row itself, String.format builds text from a pattern. The pattern "%6d\t%s" has two placeholders: %6d prints an integer in a field of at least 6 characters, padded with spaces on the left, and %s prints a string. The \t in the pattern is a real tab character.

    Step by step

    1. Create the builder. Declare a StringBuilder named sb. It collects the numbered rows.
    2. Loop by position. Write a for loop with int i from 0 while i < lines.size(). The index serves twice: for the line number and for picking the line.
    3. Separate the rows. At the top of the loop body, append "\n" when i > 0, so no row except the first starts without one and no trailing newline appears.
    4. Append the row. Format i + 1 and lines.get(i) with the pattern "%6d\t%s" and append the result. The + 1 turns the 0-based index into a line number.
    5. Return the text. After the loop, return sb.toString(). This sits outside the loop, because it runs once after every row is in.

    The solution in Java

    class Solution {
        public String numberedCat(List<String> lines) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < lines.size(); i++) {
                if (i > 0) sb.append("\n");
                sb.append(String.format("%6d\t%s", i + 1, lines.get(i)));
            }
            return sb.toString();
        }
    }
    

    The Java details worth a closer look:

    • The width in %6d is a minimum. Numbers with fewer digits are padded on the left; longer numbers are never cut. For example, String.format("%6d\t%s", 1234567, "wide") gives 1234567\twide, with all seven digits. Only inputs of a million lines or more make that happen.
    • %s and the line text. The line goes in as it is, including an empty string. A blank line becomes the number, the tab and nothing else.
    • Autoboxing. String.format takes Object arguments, so the int i + 1 is boxed into an Integer automatically. %d accepts it.
    • if without braces. if (i > 0) sb.append("\n"); controls only that one statement. The next line runs on every iteration.
    • Escapes in the pattern. "\t" inside the Java string literal is already a tab by the time format sees it; the pattern contains no backslash.

    Complexity

    Time: O(total length). Each line is visited once, and lines.get(i) is constant time for an ArrayList. Each row costs time proportional to its text plus the few digits of its number.

    Space: O(total length) for the builder and the returned string.

    A caveat about indexing: for a LinkedList, get(i) walks the list from one end, which would make the loop quadratic. A for-each loop with a separate counter avoids that, but the lesson's input is an ordinary list.

    Edge cases and common mistakes

    • Starting the numbers at 0. Writing i instead of i + 1 numbers the first line 0.
    • A newline after every row. Appending "\n" after each row, instead of before every row but the first, adds a trailing newline to the result.
    • Blank lines. ["a", "", "b"] gives " 1\ta\n 2\t\n 3\tb". The blank line keeps its number and tab.
    • Empty list. The loop never runs, so the result is "".
    • Two digits. From the tenth line on, the padding shrinks. The tenth row of a 12-line input starts with four spaces and 10, so the tabs stay in the same column as before.
    • Spaces instead of a tab. Typing spaces in the pattern gives output that looks the same on screen but differs in the characters, so the lesson's tests would fail.

    Testing

    The results below come from running the solution:

    • ["hello", "world", "foo"] gives " 1\thello\n 2\tworld\n 3\tfoo".
    • ["a", "", "b"] gives " 1\ta\n 2\t\n 3\tb".
    • [] gives "".
    • A list of twelve lines, L1 to L12, gives a result that ends with " 10\tL10\n 11\tL11\n 12\tL12".
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free