2

I was curious if, in Java, you could create a piece of code that keeps iterating a piece of code without the use of a for or while loop, and if so, what methods could be used to solve this?

sampathsris
  • 21,564
  • 12
  • 71
  • 98
NebulaeGuy
  • 169
  • 9

5 Answers5

3

Look at recursion. A recursive function is a function which calls itself until a base case is reached. An example is the factorial function:

int fact(int n)
{
    int result;

    if(n==1)
        return 1;

    result = fact(n-1) * n;
    return result;
}
ThreeFx
  • 7,250
  • 1
  • 27
  • 51
2

You could use the Java 8 Streams methods for iterating over the elements of a Collection. Among the methods you can use are filtering methods (get all the elements of a collection that satisfy some conditions), mapping methods (map a Collection of one type to a Collection of another type) and aggregation methods (like computing the sum of all the elements in a Collection, based on some integer member of the Element stored in the collection).

For example - Stream forEach :

List<Element> = new ArrayList<Element>();
...
list.stream().forEach (element -> System.out.println(element));

Or you can do it without a Stream :

List<Element> = new ArrayList<Element>();
...
list.forEach (element -> System.out.println(element));
Eran
  • 387,369
  • 54
  • 702
  • 768
1

Another variant of recursion:

public class LoopException extends Exception {
    public LoopException(int i, int max) throws LoopException {
        System.out.println( "Loop variable: "+i);
        if (i < max)
          throw new LoopException( i+1, max );
    }
}

Of course this is just a bit of fun, don't ever do it for real.

biziclop
  • 48,926
  • 12
  • 77
  • 104
1

Java does not have a goto statement (that's a lie), so that way is a dead end.

But you could always make a piece of code endlessly iterate using recursion. Old factorial function seems to be the favorite, but since it is not an infinite loop, I will go for this simple function:

int blowMyStack(int a) {
    return blowMyStack(a + 1);
}

There will be many ways to do this using various features of the language. But it always falls to an underlying recursion.

Community
  • 1
  • 1
sampathsris
  • 21,564
  • 12
  • 71
  • 98
0

In case you're referring of something like C's goto, the answer is no.

In other cases, you can use recursive functions.

Andrei B
  • 2,740
  • 17
  • 12