To create a list of numbers from 1 to N in Java, you can use a for loop to iterate from 1 to N and add each number to the list.
In this example,
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int N = 5;
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= N; i++) {
list.add(i);
}
System.out.println("List of numbers from 1 to " + N + ": " + list);
}
}
List of numbers from 1 to 5: [1, 2, 3, 4, 5]
In this tutorial, we learned How to create a List of Numbers from 1 to N in Java language with well detailed examples.