About Lesson
An array is a data structure that allows you to store a fixed-size sequential collection of elements of the same data type. You can declare an array in Java using the following syntax:
dataType[] arrayName = new dataType[arraySize];
Here, dataType
is the data type of the elements in the array, arrayName
is the name of the array, and arraySize
is the number of elements that the array can hold.
Types of Array Input
there are different ways to initialize an array with input values:
- Static initialization: In this method, the values are assigned to the array at the time of declaration. The size of the array is automatically determined by the number of values specified in the initialization. For example:
int[] numbers = {1, 2, 3, 4, 5};
- Dynamic initialization: In this method, the size of the array is specified and the values are assigned to the array using a loop or user input. For example:
Scanner input = new Scanner(System.in);
int[] numbers = new int[5];
for(int i=0; i<numbers.length; i++){
System.out.print("Enter a number: ");
numbers[i] = input.nextInt();
}
- Reading from a file: In this method, the values of the array are read from a file. For example:
try {
File file = new File("input.txt");
Scanner scanner = new Scanner(file);
int[] numbers = new int[5];
int i = 0;
while (scanner.hasNextInt() && i < numbers.length) {
numbers[i++] = scanner.nextInt();
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
- Command line arguments: In this method, the values of the array are passed as command line arguments. For example:
public static void main(String[] args) {
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; i++) {
numbers[i] = Integer.parseInt(args[i]);
}
}
Join the conversation