Java Arrays
Java Arrays
In Java, an array is a data structure used to store multiple values of the same
data type in a single variable. Instead of declaring separate variables for each
value, arrays provide an efficient way to manage collections of data.
Declaring and Initializing Arrays
Declaring an Array
An array is declared by specifying the data type followed by square brackets []
and the variable name:
At
this stage, the array is only declared but not initialized.
Initializing an Array
To assign values, you can initialize the array at the time of declaration:
Alternatively, you can create an array of a fixed size and assign values later:
Modifying an Array
You can update the value of any element by referencing its index:
Itera
ting Over a 2D Array
Usi
ng a For-Each Loop
Key Takeaways
✅ Arrays efficiently store multiple values of the same type.
✅ Elements are accessed using zero-based indexing.
✅ The .length property returns the total number of elements.
✅ For and for-each loops simplify working with arrays.
✅ Multidimensional arrays help organize complex data structures.