Categories
Java

Yield in Java 14

The “yield” statement allows you to return a value from a method that uses the yield keyword and it also allows the method to be resumed later on, when the next value is requested.

This allows you to implement a simple form of generator, which can be useful when you want to generate a sequence of values without having to create an explicit data structure to hold all of the values.

Here’s an example why to use the yield statement:

class PrimeNumbers {
    static Iterator<Integer> sequence() {
        int current = 2;
        while (true) {
            boolean isPrime = true;
            for (int i = 2; i <= Math.sqrt(current); i++) {
                if (current % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                yield current;
            }
            current++;
        }
    }
}

In this example, we are creating an Iterator that generates the prime numbers, the method sequence uses the yield statement to return the next prime number in the sequence and the method will be resumed when the next value is requested.

Without using the yield statement, we would have to create an explicit data structure, like an array, to hold all of the prime numbers, and it would consume more memory and resources, also it would make the code more complex and harder to read.

By using the yield statement, we don’t have to create an explicit data structure to hold all of the prime numbers, and it consumes less memory and resources, also it makes the code more readable and efficient, as the method only generates the next prime number when it’s requested.

It’s worth noting that testing code that uses the yield statement can be more difficult as well, as the code can have multiple execution paths depending on the values requested.

Leave a Reply

Your email address will not be published. Required fields are marked *