Understanding Scanner’s nextLine(), next(), and nextInt() methods

nextLine() reads the remainder of the current line even if it is empty.

Correct.

nextInt() reads an integer but does not read the escape sequence “\n”.

Correct1.

next() reads the current line but does not read the “\n”.

Incorrect. In fact, the next() method reads the next complete token. That may or may not be the rest of the current line. And it may, or may not consume an end-of line, depending on where the end-of-line is. The precise behavior is described by the javadoc, and you probably need to read it carefully for yourself in order that you can fully understand the nuances.

So, in your example:

  1. The nextInt() call consumes the 2 character and leaves the position at the NL.

  2. The next() call skips the NL, consumes H and i, and leaves the cursor at the second NL.

  3. The nextLine() call consumes the rest of the 2nd line; i.e. the NL.


1 … except that your terminology is wrong. When the data is being read, it is not an escape sequence. It is an end-of-line sequence that could consist of a CR, a NL or a CR NL depending on the platform. The escape sequences you are talking about are in Java source code, in string and character literals. They may >>represent<< a CR or NL or … other characters.

Leave a Comment