Java Code Example: for loop to store even and odd items in lists

The code defines a class called “EvenOddItems”. This class contains a main method, which is the entry point of the program.

In the main method, two integer variables odd and even are declared and initialized to 0.

Next, two ArrayLists oddNumbers and evenNumbers are created to store the odd and even numbers, respectively.

A for loop is used to iterate over the numbers from 0 to 19 (inclusive). In each iteration, the value of i is checked to see if it is an even number or an odd number. If i is even, it is added to the evenNumbers list and the value of even is incremented by i. On the other hand, if i is odd, it is added to the oddNumbers list and the value of odd is incremented by i.

Finally, the values of the evenNumbers and oddNumbers lists and their sums are printed to the console. The toString method is used to convert the lists to a string representation so that they can be printed to the console.

import java.util.ArrayList;
import java.util.List;

class EvenOddItems {
    public static void main(String[] args) {
        int odd = 0, even = 0;

        List<Integer> oddNumbers = new ArrayList<>();
        List<Integer> evenNumbers = new ArrayList<>();

        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                even += i;
                evenNumbers.add(i);
            } else {
                odd += i;
                oddNumbers.add(i);
            }
        }

        System.out.println("Even Numbers: " + evenNumbers.toString());
        System.out.println("Sum of even numbers: " + even);
        System.out.println("Odd Numbers: " + oddNumbers.toString());
        System.out.println("Sum of odd numbers: " + odd);
    }
}
Output
Even Numbers: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Sum of even numbers: 90
Odd Numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Sum of odd numbers: 100