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:
Accessing and Modifying Array Elements
Accessing Elements
Arrays use zero-based indexing, meaning the first element is at index 0:
Modifying an Array
You can update the value of any element by referencing its index:
Determining Array Length
To find out how many elements an array contains, use the .length property:
Looping Through an Array
Using a For Loop
A for loop is commonly used to iterate over an array by accessing elements
with their index:
Using a For-Each Loop
A for-each loop provides a simpler way to iterate through an array without
dealing with indexes:
Real-World Examples Using Arrays
Finding the Average of Numbers in an Array
Finding the Smallest Value in an Array
Working with Multidimensional Arrays
A multidimensional array is an array containing multiple arrays, useful for
handling structured data like tables or matrices.
Declaring and Initializing a 2D Array
Accessing Elements in a 2D Array
Each element is identified using row and column indices:
Itera
ting Over a 2D Array
Using Nested For Loops
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.