Skip to content
Sharp

Core Java · interview question

What will happen if you try to read an integer input using Scanner's nextInt() when the input is non-numeric?

Multiple choiceHardchapter-1-curatedpremiumcore-javaconsole-input-and-output
java
Scanner scanner = new Scanner(System.in);
try {
  int number = scanner.nextInt();
} catch (InputMismatchException e) {
  System.out.println("Please enter a valid number.");
}
Choose one answer
Answer and explanation

Correct answer

C. It throws an InputMismatchException.

Why

The 'nextInt()' method expects numeric input. If the input is non-numeric, it will throw an 'InputMismatchException', indicating that the input does not match the expected type.

Test yourself on Core Java

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

Start free test
All Core Java questions →