MCQ Single Best Answer Moderate

Q
[Object Oriented Programming]

Which one of the given exceptions is raised when a user enters a String literal "hello" during execution of the following code?
import java.util.*;
class Message
{
    public void doIt()
    {
        System.out.println("Enter a message");
        int s = (new Scanner(System.in)).nextInt();
        System.out.println(s);
    }
}

ID: #24948 Competency focused Practice Questions ISC Class XII Computer Science 2 views
Question Info
#24948Q ID
ModerateDifficulty
Competency focused Practice Questions ISC Class XII Computer ScienceTopic

Choose the Best Option

Click any option to instantly check if you're correct.

  • A InputMismatchException
  • B InputFormatException
  • C NullPointerException
  • D NumberFormatException
Correct Answer: Option A

Explanation

[Object Oriented Programming]

Which one of the given exceptions is raised when a user enters a String literal "hello" during execution of the following code?
import java.util.*;
class Message
{
    public void doIt()
    {
        System.out.println("Enter a message");
        int s = (new Scanner(System.in)).nextInt();
        System.out.println(s);
    }
}
(a) InputMismatchException
(b) InputFormatException
(c) NullPointerException
(d) NumberFormatException
Correct Answer: (a) InputMismatchException

Step-by-Step Explanation:

Step 1: Understanding the Code

The program uses the Scanner class to take input from the user:

int s = (new Scanner(System.in)).nextInt();

The method nextInt() expects an input of type integer.

Step 2: What User Inputs?

The user enters:

hello

This is a String, not an integer.

Step 3: What Happens Internally?

  • nextInt() tries to convert input into an integer
  • But "hello" cannot be converted to a number
  • So Java throws an exception

Which Exception is Thrown?

The Scanner class throws:

InputMismatchException

when the input does not match the expected data type.

Why Other Options are Incorrect?

  • InputFormatException → Not a standard Java exception
  • NullPointerException → Occurs when accessing null reference, not input mismatch
  • NumberFormatException → Occurs when manually converting string to number (e.g., Integer.parseInt()), not with Scanner.nextInt()

Important Note:

Exception behavior differs based on method used:

Method Exception Type
Scanner.nextInt() InputMismatchException
Integer.parseInt() NumberFormatException

Conclusion:

Since nextInt() receives invalid (non-integer) input, Java throws:

InputMismatchException

Therefore, the correct answer is: (a)

Share This Question

Challenge a friend or share with your study group.