NoSuchElementException in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Overview

NoSuchElementException() is an exception thrown in Java by the next() or the nextElement method(). This is thrown when there is no impending element left in an enumeration. It is often shown when the user is trying to access the elements of an empty object, or when trying to get the subsequent element in a collection of objects which has already been traversed till the end.

Introduction

nosuchelementexception() is a runtime exception and occurs at the time of execution of the code. It is an unchecked exception, which means that is not checked at compile time. Errors and runtime exceptions are categorized as unchecked exceptions.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

Declaration

The exception is declared in the following manner, followed by the source of the error.

Constructor's Summary

ConstructorDescription
NoSuchElementException()This method constructs a NoSuchElementException free from any error message
NoSuchElementException(String s)It constructs a NoSuchElementException. It contains a message string s saved as a reference for the error for later retrieval by the getMessage method

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Constructor in Java

A constructor in Java is a block of code similar to a method. When a new instance of the class is created, it is called. The object's memory is allocated when the function constructor is called. It is a type of method that is used to initialize an object.

At least one constructor is called every time an object is created with the new() keyword.

If there is no constructor in the class, it calls the constructor. In this case, the online Java compiler automatically provides a default constructor.

In Java, there are two kinds of constructors: no-arg constructors and parameterized constructors.

Defining a constructor is subject to three rules: The constructor's name must be the same as the name of the class. There must be no explicit return type in a Constructor. An abstract, static, final, or synchronized Java constructor is not allowed.

Methods of NoSuchElementException()

MethodDescription
NoSuchElementException()It constructs a NoSuchElementException method without a string error message.
NoSuchElementException (String s)It constructs a NoSuchElementException method with a message string s saved as a reference to the error for retrieval later by the getMessage method. The string s contains the name of the class that causes the error.

What Causes java.util.NoSuchElementException()

The NoSuchElementException is thrown by the nextElement() method of an Enumeration, indicating that there are no more elements in the enumeration. The following methods throw the NoSuchElementException:

  • nextElement() of Enumeration interface
  • next() of NamingEnumeration interface
  • nextElement() of StringTokenizer class
  • next() of Iterator interface

One of the most typical causes of the NoSuchElementException is when we iterate over an empty Set. We may avoid this exception by adding a check before iterating through the set. While iterating, check every time that an element is present in the set and then do the following-

This method ensures that any element, if it exists, is accessed.

Examples of NoSuchElementException()

Example 1

In the following example, we are attempting to access a HashMap via the Iterator class's accessor method next(), but because the HashMap is empty, we will receive a NoSuchElementException.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Java Program to Demonstrate the Occurrence of NoSuchElementException()

Example 2

In the Following Example, We're Attempting to Use an Enumerator to Access an Element of an Empty Vector Object.

How to Fix java.util.NoSuchElementException?

Almost all classes whose accessor methods throw NoSuchElementException provide a way to determine whether the object has more elements or not. To avoid this NoSuchElementException, we must always call --

Iterator.hasNext() or Enumeration.hasMoreElements() or hasMoreToken() method before calling next( ) or nextElement or nextToken() method.

The below examples demonstrate how NoSuchElementException can be fixed:

Example 1

Java Program that Uses hasNext to Prevent the Occurrence of NoSuchElementException()

The code shown above demonstrates the use of the hasNext() method. This allows the user to first check if a successive element is present and then only use the .next() method to avoid the NoSuchElementException().

Example 2

Here is a Java Program that Uses hasMoreElements to Prevent the Occurrence of NoSuchElementException().

The code shown above demonstrates the use of the hasMoreelements() method. This allows the user to first check if a successive, vectorial object is present and then only use the .next() method to avoid the NoSuchElementException().

Conclusion

  1. NoSuchElementException is an exception thrown in Java by the next() or the nextElement method()
  2. It is often shown when the user is trying to access the elements of an empty object, or when trying to get the subsequent element in a collection of objects which has already been traversed till the end.
  3. It is a runtime, unchecked exception.
  4. Iterator.hasNext() or Enumeration.hasMoreElements() or hasMoreToken() method before calling next( ) or nextElement or nextToken() method could be used to avoid NoSuchElementException.
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more