Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

JD.NEXT

JD.NEXT occurs when an Iterator.next() is called without a preceding hasNext().

Vulnerability and risk

A 'next()' method can throw a NoSuchElement exception if there are not enough elements in the collection.

Mitigation and prevention

If an exception is expected, mark your method as throwing a java.util.NoSuchElementException. Otherwise, it is better to add an explicit check for iter.hasNext instead of collection.size(), to avoid a time-to-check time-to-use race condition. Even if you think that this method is not mult-ithreaded, it will improve the readability and maintainability of the code.

Example 1

11     public boolean intersects(Set setA, Set setB) {
12         for (final Iterator iteratorA = setA.iterator(); iteratorA.hasNext();) {
13             final Object a = iteratorA.next();
14             for (final Iterator iteratorB = setB.iterator(); iteratorB.hasNext();) {
15                 Object b = iteratorA.next();
16                 if (a.equals(b)) {
17                     return true;
18                 }
19             }
20         }
21         return false;
22     }

JD.NEXT is reported for the snippet on line 15: method 'next()' is called for 'iteratorA' without a preceding 'hasNext()' check. You may have intended to call the 'next()' method for 'iteratorB' instead of 'iteratorA'.

Example 2

11     public boolean intersects(Set setA, Set setB) {
12         for (final Iterator iteratorA = setA.iterator(); iteratorA.hasNext();) {
13             final Object a = iteratorA.next();
14             for (final Iterator iteratorB = setB.iterator(); iteratorB.hasNext();) {
15                 Object b = iteratorB.next();
16                 if (a.equals(b)) {
17                     return true;
18                 }
19             }
20         }
21         return false;
22     }

The snippet from the previous section is fixed; all calls to 'next' are preceded with appropriate 'hasNext' checks. JD.NEXT is not reported here.

Extension

This checker can be extended through the Klocwork knowledge base. See Tuning Java analysis for more information.