Iterators - in COBOL and Java

COBOL Java
      $set sourceformat(free)
class-id sillyCount.
working-storage section.
01 c binary-long value 1 static.

method-id main (cmds as string occurs any) static.
    *> Use perform to loop over an iterator
    perform varying i as binary-long through self::doCount()
        display i
    end-perform
    display space
    declare o = new self
    perform varying i as binary-long through o
        display i
    end-perform
end method.
           
*> Create an iterator by using iterator-id instead of method-id
iterator-id doCount static.
    *> The return value of the iterator is defined using the
    *> yielding keyword
procedure division yielding j as binary-long.
    perform until false
        add 1 to c
        move c to j
        *> Until the iterator is stopped, it will yield on
        *> a goback verb, equivalent to exit iterator
        goback

        *> ...and then start again directly after the goback 
        *> on the next invocation of the iterator
        multiply c by 10 giving j
        if c less then 5
            goback
        else
            *> Stop iterator - as it says
            *> Control goes back to the calling routine.
            stop iterator
            goback
       end-if
    end-perform
    *> COBOL will implicitly stop iterator at the 
    *> end of the iterator definition. 
    *> In this example – the code never gets here.
end iterator.

    *> Create an iterator directly for an instance of this class
    *> Note use of 'self' keyword instead of giving the iterator a name
iterator-id self yielding j as binary-long.
    perform varying j from 23 by -5 until j < 0
           exit iterator
    end-perform
end iterator.
end class.
In Java there is no YIELD feature, so the iterator
implementation has to take care of state.

Portions of these examples were produced by Dr. Frank McCown, Harding University Computer Science Dept, and are licensed under a Creative Commons License.