Explanation
Here is an explanation of the program formatted for learning:
1. Purpose
This program demonstrates how to create a pre-defined (static) one-dimensional integer array in Java and print all of its elements to the console using a for loop.
2. Key Concepts
- 1D Array: A data structure that stores a fixed-size sequence of elements of the same type.
- Static Initialization: Directly assigning values to an array at the time of creation using curly braces
{}. - Array Indexing: Accessing elements by their position, starting at index
0up tolength - 1. - Array Length (
.length): A built-in property that returns the total number of elements in an array.
3. Code Walkthrough
int[] num = {2, 5, 7, 12, 10};Declares an integer array namednumand fills it with 5 static values.System.out.print("Static 1D Array: [");Prints the label and the opening bracket without creating a new line.for(int i = 0; i < num.length; i++)Aforloop that starts at index0and runs as long asiis less thannum.length(which is5).System.out.print(num[i] + ", ");Accesses the value at the current indexnum[i]and prints it followed by a comma.System.out.println("]");Prints the closing bracket and moves the cursor to a new line.
4. Output
Static 1D Array: [2, 5, 7, 12, 10, ]