You indeed need to use the args
variable. Parameters you pass to the Java program are stored into the args
variable by the JVM, making them available for the programmer.
I assume one parameter (the intended array size) is passed to the program, and that will be args[0]
.
You need to parse this String as an int, and use that number as array size:
// We assume args[0] exists and can be parsed as an integer, or else a
// NumberFormatException will be thrown
int size = Integer.valueOf(args[0]);
// We can use the size variable as array size.
int[] m = new int[size];
Now the array m
has a size of the number given through the command line. Notice that the array size is not known at compile time, only at runtime. An array cannot be resized once created. Its length can be retrieved using m.length
. Its values are initialized to 0
.
If you want to print each element of the array, you can use
a for loop:
for (int i = 0; i < m.length; i++) { // Loop variables are often called i
// System.out.println prints its argument to the console
System.out.println(m[i]);
}
or an enhanced for loop (also known as a foreach loop):
for (int n : m) {
System.out.pritnln(n);
}
or using Java Streams:
either
Arrays.stream(m).forEach(System.out::println);
or
IntStream.of(m).forEach(System.out::println);
More about memory allocation: