how to add elements in array in java using for loop

how to add elements in array in java using for loop

To add elements to an array in Java using a for loop, you can use a counter variable to keep track of the current index in the array, and use the assignment operator = to add the elements to the array.

Here's an example of how you could use a for loop to add elements to an array in Java:

public class Main {
  public static void main(String[] args) {
    int[] numbers = new int[5];
    for (int i = 0; i < numbers.length; i++) {
      numbers[i] = i + 1;
    }
    System.out.println(Arrays.toString(numbers));
  }
}
Source‮.www:‬lautturi.com

In this example, the numbers array is initialized with a length of 5. The for loop iterates over the elements of the array, starting from index 0 and ending at index 4. On each iteration, the loop assigns the value of the counter variable i plus 1 to the current element of the array.

The output of this example would be the following array:

[1, 2, 3, 4, 5]

Keep in mind that the for loop in this example assumes that the array has already been initialized with a length. If you want to add elements to an array dynamically, you can use a different approach, such as using a collection class, such as ArrayList, or creating a new array and copying the elements manually.

Here's an example of how you could use an ArrayList to add elements to an array dynamically:

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<>();
    for (int i = 1; i <= 5; i++) {
      list.add(i);
    }
    int[] numbers = list.stream().mapToInt(i -> i).toArray();
    System.out.println(Arrays.toString(numbers));
  }
}

In this example, the ArrayList object named list is initialized with no elements. The for loop iterates over the elements from 1 to 5, and adds each element to the list using the add method. Then, the stream method is used to create a stream of the elements in the list, and the mapToInt and toArray methods are used to convert the stream to an int array. Finally, the Arrays.toString method is used to print the numbers array as a string.

The output of this example would be the same as the previous example:

[1, 2, 3, 4, 5]

Keep in mind that the ArrayList class is part of the java.util package, which is included in the standard Java SE library. You can use a similar approach to add elements to an array dynamically using other collection classes, such as LinkedList, Vector, or Queue.

Created Time:2017-11-01 12:05:10  Author:lautturi