Skip to content
Sharp

Core Java · interview question

In a console application, what common issue arises when using Scanner's nextLine() method after nextInt()?

Multiple choiceHardchapter-1-curatedpremiumcore-javaconsole-input-and-output
java
Scanner scanner = new Scanner(System.in);
int quantity = scanner.nextInt();
scanner.nextLine(); // Consume newline
String productName = scanner.nextLine();
Choose one answer
Answer and explanation

Correct answer

C. It reads an empty line.

Why

After using 'nextInt()', a newline character is left in the input buffer, causing 'nextLine()' to read it as an empty line. To solve this, you can add an additional 'nextLine()' call to consume the newline.

Test yourself on Core Java

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

Start free test
All Core Java questions →