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);
}
}
Which one of the given exceptions is raised when a user enters a String literal "hello" during execution of the following code?
class Message
{
public void doIt()
{
System.out.println("Enter a message");
int s = (new Scanner(System.in)).nextInt();
System.out.println(s);
}
}
Question Info
Choose the Best Option
Click any option to instantly check if you're correct.
Explanation
Which one of the given exceptions is raised when a user enters a String literal "hello" during execution of the following code?
class Message
{
public void doIt()
{
System.out.println("Enter a message");
int s = (new Scanner(System.in)).nextInt();
System.out.println(s);
}
}
Step-by-Step Explanation:
Step 1: Understanding the Code
The program uses the Scanner class to take input from the user:
The method nextInt() expects an input of type integer.
Step 2: What User Inputs?
The user enters:
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:
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:
Therefore, the correct answer is: (a)
Share This Question
Challenge a friend or share with your study group.