Skip to content
Sharp

Core Java · interview question

Consider this code: 'Scanner scanner = new Scanner(System.in); int value = scanner.nextInt(); scanner.nextLine();'. What problem does adding 'scanner.nextLine()' solve?

Multiple choiceHardchapter-1-curatedpremiumcore-javaconsole-input-and-output
Choose one answer
Answer and explanation

Correct answer

D. It clears the newline character left in the buffer.

Why

After calling 'nextInt()', the newline character from pressing 'Enter' remains in the buffer. Calling 'nextLine()' immediately after consumes this leftover newline, preventing potential input issues when reading strings subsequently.

Test yourself on Core Java

A free test with instant, explained results. No account needed.

Start free test
All Core Java questions →