Start learning free

LESSON 614 OF 671 · PROJECTS: COMMAND-LINE TOOLS

wc Character Count in Java: Summing Line Lengths

Practice Read the full explanation

Build a tiny version of the character count of the Unix wc command. Given a list of lines, return the total number of characters across all lines as an integer.

Convention: count only the characters in each line — do not count the implicit newlines that separate them. Spaces and tabs inside a line count as one character each.

Note: this is a simplified version. The real wc -m also counts the newlines, and the real wc -c counts bytes, not characters. Here the answer is simply the sum of the line lengths. The input is plain ASCII text (other alphabets are counted differently by different languages).

Function signature:

public int countChars(List<String> lines)

Example:

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

Output: 10

"hello" has 5 chars and "world" has 5 chars, for a total of 10.

An empty line adds 0, and an empty list of lines gives 0.


Loop through the lines and accumulate line.length() into an int running total.

The full solution:
class Solution {
    public int countChars(List<String> lines) {
        int total = 0;
        for (String line : lines) {
            total += line.length();
        }
        return total;
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Wc V3 in Java, explained

    Problem overview

    The method countChars takes a List<String> of lines and returns the total number of characters across all of them. This is a simplified version of the character count in the Unix wc command, with one convention: only the characters inside each line count, not the newlines that separate lines. The answer is simply the sum of the line lengths. Spaces and tabs inside a line count as one character each.

    For ["hello", "world"] the answer is 10, since each word has 5 characters. An empty line adds 0, and an empty list gives 0.

    Approach: one running total

    There is nothing to cut apart or compare here. Visit every line, ask it for its length, and add that to a total. The version before this one needed a split to find words, but characters are already available through length().

    Step by step

    1. Create total, an int that starts at 0. A sum always starts at zero, before any line has been added, and that is also the right answer for an empty list.
    2. Loop over the lines with a for-each loop, taking each entry as the String line.
    3. Add the line's length. line.length() is the number of characters in that one string, so total += line.length() grows the sum by exactly that much.
    4. Return total after the loop, so the return happens once, when every line has been counted.

    The solution in Java

    class Solution {
        public int countChars(List<String> lines) {
            int total = 0;
            for (String line : lines) {
                total += line.length();
            }
            return total;
        }
    }
    

    A few Java details:

    • Strings use length(), arrays use length. A String has a method, so it needs the parentheses. Writing line.length without them does not compile.
    • What length() counts. It counts UTF-16 code units. For plain ASCII text, which is all this lesson uses, that is the same as the number of characters. A single emoji such as "\uD83D\uDE00" has a length of 2, so for text outside ASCII the result would differ from what a person would count.
    • The int total. It can hold values up to about 2.1 billion. Test inputs are far smaller, but a total over that limit would wrap around silently.
    • List needs an import. In a standalone file, add import java.util.List;.

    Edge cases and common mistakes

    • Empty lines and an empty list. ["", ""] and [] both return 0. The first loop adds two zeros, the second does not run at all.
    • Whitespace counts. ["a b\tc", ""] returns 5: three letters, one space and one tab. Do not trim the line, because trimming would remove characters that the count is supposed to include. [" "] returns 2.
    • Counting newlines. Adding 1 per line for a separator is what the real command does, but not what this lesson asks for.
    • Returning inside the loop. A return placed before the closing brace of the loop would stop after the first line.

    Testing

    • ["hello", "world"] gives 10.
    • ["a b\tc", ""] gives 5.
    • [" "] gives 2.
    • ["", ""] gives 0.
    • [] gives 0.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free