Is there an incompatibility in LineNumberReader in Java 17?

Viewed 46

suggest the snippet below: Basically, it reads the string One\nTwo completely, piping it through a LineNumberReader. So far, nothing special. Problem: On Java 8, and Java 11, the output is 1. On Java 17, however, the output is 2. (Looks, like the last, unterminated line is counted in the latter case, but isn't in the former cases.

Question: Is this a known incompatibility? Is it documented, and intentional?

Thanks,

Jochen

    final StringReader sr = new StringReader("One\nTwo");
    final LineNumberReader lnr = new LineNumberReader(sr);
    for (;;) {
        final int c = lnr.read();
        if (c == -1) {
            System.out.println("Line number=" + lnr.getLineNumber());
            break;
        }
    }
1 Answers

Looks intentional to me as the Java 17 docs for read show the difference:

Java 8

Read a single character. Line terminators are compressed into single newline ('\n') characters. Whenever a line terminator is read the current line number is incremented.

Java 11

Read a single character. Line terminators are compressed into single newline ('\n') characters. Whenever a line terminator is read the current line number is incremented.

Java 17

Read a single character. Line terminators are compressed into single newline ('\n') characters. The current line number is incremented whenever a line terminator is read, or when the end of the stream is reached and the last character in the stream is not a line terminator.

Related