Home » Java » Get even numbers between given range – java

Get even numbers between given range – java

In this tutorial, you will learn how to get all the even numbers between a given range using java.

In this case, I created a class call EvenNumbers and a static method call getEven. We can call static methods directly without creating objects in java. Because of clarity, here I created getEven method as a help-method.

I declared two variables “left” and “right” by assigning 3 and 9. Those are the given boundaries. In the other hand, we have to find all the even numbers within 3 and 9.

Here, the for loop runs from left boundary to right boundary. Inside that for loop, there is a condition to check even numbers. In programming, % is an operator call modules operator. It will give remainder after division of one number by another.

So, to get even numbers, the remainder of the division of each number within the given rage should be equal to zero. That the logic we use here in line 1.

public class EvenNumbers {

    public static void main(String[] args) {
        
        getEven();
        
    }

    static void getEven() {
        int left = 3;
        int right = 9;
                
        for (int i = left; i < right + 1; i++) {
           if (i % 2 == 0){ // line 1
               System.out.println(i);
           }
        }
    }
}
Please follow us:
error

Leave a Reply

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

*
*

FACEBOOK
FACEBOOK
YOUTUBE
YOUTUBE