Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is InputMismatch Exception in Java?
2.1.
Example
2.2.
Java
3.
What Causes InputMismatchException
3.1.
Class Hierarch
3.2.
Constructors
4.
Methods of java.lang.Object Class
5.
Methods of java.lang.Throwable Class
6.
When does InputMismatchException occur?
6.1.
Java
7.
Handling of the Exception
7.1.
Java
8.
Frequently Asked Questions
8.1.
Why is exception handling necessary?
8.2.
How can the InputMismatchException java class access methods of the Object and Throwable class?
8.3.
What is the importance of Scanner class in Java?
8.4.
How do you handle InputMismatchException in Java?
8.5.
What is the difference between NumberFormatException and InputMismatchException?
9.
Conclusion
Last Updated: Mar 29, 2024
Medium

InputMisMatchException in Java

Author Manish Kumar
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Ever typed something into a program and gotten a weird error message? In Java, it might be because of an "InputMismatchException." This happens when your program asks for a number, but you accidentally type a word or something else. Don't worry, this blog will explain what this error means and how to avoid it.

InputMismatch Exception in Java

In this blog, we will discuss the input mismatch exception in Java. We will learn about the class hierarchy of the input mismatch exception, exception handling and the methods of the object and throwable class.

Must Read, Multithreading in java, Duck Number in Java

What is InputMismatch Exception in Java?

What is InputMismatch Exception in Java?

 

The input mismatch exception is thrown when the input given by the user does not match the expected input type. Let's understand this exception with the help of an example: 

Example

  • Java

Java

import java.util.Scanner;

class Ninja_Learning_Java {

public static void main(String[] args) {
System.out.println("Enter your age:");
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
System.out.println("Your age is:" + age);
sc.close();
}
}

✅ Output: When the user has given correct integer input.

Output

 

✅ Output: When the input is a string, but the expected value is an integer.

Output

In the above program, our prime aim was to get the "age" as input from the user, which should be an integer. We created a scanner object for our purpose and called the nextInt() function to take the input. Initially, an integer input was given and in the next run, a string input.

From the code above, we can conclude the following things:

💧When the input is of the expected type, the program works correctly.

💧When the input is not the expected type, the program throws the InputMismatchException.
 

Note: The InputMismatch Exception is an unchecked exception and a subclass of the java.lang.RuntimeException. The InputMismatch Exception is a subclass of throwable and object class and thus inherits all the methods of these classes.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What Causes InputMismatchException

This error pops up when there's a clash between the kind of information your program expects and what you actually give it. Here's the breakdown:

  • The program asks for a number: Imagine your program needs your age. It expects a number like 25.
  • Surprise! You give it words: But you accidentally type "twenty five".

Since the program was looking for a number, this mismatch throws the "InputMismatchException." It's like the program saying, "Hey, that's not what I was expecting!"

Class Hierarch

Class Hierarch

Constructors

The InputMismatchException class has two constructors.

InputMismatchException()

It creates an input mismatch exception with null as the error message.

InputMismatchException(String s)

It creates the input mismatch exception and saves the reference to the error message "s" so that it can later be retrieved using the getMessage() method.

Also see,  Swap Function in Java

Methods of java.lang.Object Class

The object class is the default parent of the classes in Java. It is the topmost class. Since all the classes inherit from this base class, it is beneficial to know the methods it offers. Our InputMismatchException java class is a subclass of the object class. Let's see the methods provided by the object class.

MethodDescription
getClass()It returns the class object of the specified object.
toString()Returns the string representation of the object.
hashCode()Returns the hash code value for the object.
equals()Compares the given object to this object and returns true if they are equal, false otherwise.
clone()Returns an exact copy of the object.
notify()Wakes up a single thread that is waiting on this object's monitor.
notifyAll()Wakes up all threads that are waiting on this object's monitor.
wait()Makes the current thread wait for a certain period of time.
finalize()It is invoked by the garbage collector before the object is removed from memory.

Methods of java.lang.Throwable Class

The throwable class is the superclass of all Java errors and exception classes. Only those classes which are instances of this class or one of its subclasses can generate exceptions throwable by the Java Virtual Machine. The InputMismatchException class is a subclass of the throwable class, and thus, all the methods are inherited. Let's see the methods available in the throwable class.

MethodDescription
getCause()Returns the cause of the throwable, or null if there isn't one. Throwable is the superclass of exceptions and errors.
fillInStackTrace()Initializes the stack trace information for the throwable.
getLocalizedMessage()Creates a message describing the throwable in the current locale.
getMessage()Returns the detailed message string of the throwable.
getStackTrace()Returns an array of StackTraceElement objects that represent the stack trace.
printStackTrace()Prints the throwable and its backtrace to the standard error stream.
toString()Returns a string containing a concise description of the throwable.
setStackTrace()Sets the stack trace elements for the throwable.

When does InputMismatchException occur?

The Scanner object matches the input token to the expected token type, and when there is a mismatch, it throws the InputMismatchException java error. It is also thrown when the input is out of range. The Java.util package contains the Scanner class.

Mismatch Example

 

Example: If the expected input type is float and the user inputs a string, the compiler will throw the input mismatch exception. Another possible scenario would be when the user inputs out of range floating point values. 

  • Java

Java

//program to understand inputmismatchexception java
import java.util.InputMismatchException;
import java.util.Scanner;

class Ninja_Learning_Java {

public static void main(String[] args) {
// Running the code twice, once with the correct input and the other out of range

// Creating the scanner object
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
// Prompting the user to enter an integer
System.out.println("Enter your age:\n");

try {
//Taking input from the user
int age = sc.nextInt();

System.out.println("Your age is:" + age + "\n");
} catch (InputMismatchException java_error) {

// Printing the error
System.out.println(java_error);
}
}

sc.close();
}
}

Output:

Output

Practice by yourself on java online compiler.

Handling of the Exception

The simplest way to handle this exception is to give correct input. That's all!!

But you know what? The user might need to be made aware of the input type due to a variety of reasons. Therefore it becomes crucial to handle this exception smartly. We can create an alert if the user gives the wrong input. Let's understand this using the code shown below, which will slightly modify the code provided in the previous section.

  • Java

Java

//program to understand input mismatch exception handling
import java.util.InputMismatchException;
import java.util.Scanner;

class Ninja_Learning_Java {

public static void main(String[] args) {
// creating the scanner object
Scanner sc = new Scanner(System.in);

// running a while loop until correct input is not found
while (true) {
try {
// prompting the user to enter an integer
System.out.println("Enter your age:");

// Taking input from the user
int age = sc.nextInt();
System.out.println("Your age is:" + age + "\n");

break;
} catch (InputMismatchException java_error) {
// printing the error
System.out.println(
"Please enter the age as an Integer and not anything else. Thank You !"
);
}

sc.nextLine();
}

sc.close(); // Closing the Input Stream
}
}

Must Read: Java System Out Println and Hashcode Method in Java

Output:

Output

We can even create custom behaviour based on the type of input the user gives to make the exception handling more robust. Exception handling will improve the user experience and make the application crash-resistant.

Must Read What are Loops in Java.

Frequently Asked Questions

Why is exception handling necessary?

Exception handling saves the application from crashing. It provides a solution for errors that occur while running the program. Moreover, it improves the user experience by providing smooth behaviour.

How can the InputMismatchException java class access methods of the Object and Throwable class?

The InputMismatchException is a child class of both Object and Throwable class and thus inherits their behaviour.

What is the importance of Scanner class in Java?

It is a class provided by java.util package and gives us a way to take input from the user.

How do you handle InputMismatchException in Java?

Use a try-catch block to catch the exception and prompt the user to enter valid data.

What is the difference between NumberFormatException and InputMismatchException?

InputMismatchException occurs for any data type mismatch, while NumberFormatException is specific to errors in converting a String to a numeric type.

Conclusion

We extensively discussed the InputMismatchException Java Class. The class hierarchy and methods inherited were also discussed. We also learned how to handle the inputmismatchexception java gracefully and saw the constructors.

More blogs on Java:

You can find more Maven blogs on our platform: Coding Ninjas Studio.

To excel in the technical field, visit our platform Coding Ninjas Studio to learn more about JavaScript, DSA, Competitive Programming, System Design, etc. Enroll in our courses and refer to the mock test and problems available. To prepare for placements, follow our interview experiences and interview bundle curated especially for cracking technical jobs.

Happy Coding!

Previous article
Decoding throw and throws keywords in Exception Handling|Part-4
Next article
Exception Handling In Java Using Try-Catch And Finally
Live masterclass