Ask Question
31 October, 01:03

Write a program that adds the numbers 1 through 5 into the numbers ArrayList and then prints out the first element in the list.

+5
Answers (1)
  1. 31 October, 03:32
    0
    Answer code is given below along with comments to explain each step

    Explanation:

    Method 1:

    / / size of the array numbers to store 1 to 5 integers

    int Size = 5;

    / / here we have initialized our array numbers, the type of array is integers and size is 5, right now it is empty.

    ArrayList numbers = new ArrayList (Size);

    / / lets store values into the array numbers one by one

    numbers. add (1)

    numbers. add (2)

    numbers. add (3)

    numbers. add (4)

    numbers. add (5)

    / / here we are finding the first element in the array numbers by get () function, the first element is at the 0th position

    int firstElement = numbers. get (0);

    / / to print the first element in the array numbers

    System. out. println (firstElement);

    Method 2:

    int Size = 5;

    ArrayList numbers = new ArrayList (Size);

    / / here we are using a for loop instead of adding manually one by one to store the values from 1 to 5

    for (int i = 0; i < Size; i++)

    {

    / / adding the values 1 to 5 into array numbers

    numbers. add (i);

    }

    //here we are finding the first element in the array numbers

    int firstElement = numbers. get (0);

    / / to print the first element in the array

    System. out. println (firstElement);
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write a program that adds the numbers 1 through 5 into the numbers ArrayList and then prints out the first element in the list. ...” in 📘 Engineering if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers