Java Arrays
📦 Java Arrays
An array in Java is a container object that holds a fixed number of values of the same type.
Arrays are zero-indexed, meaning the first element is at index 0.
✅ 1. Declaration and Initialization
Syntax:
Or combined:
Example 1: Declare an integer array
Example 2: Declare and initialize together
✅ 2. Array Length
📌 Output:
✅ 3. Looping Through an Array
Using for loop:
Using for-each loop:
✅ 4. Array of Objects (Strings Example)
📌 Output:
✅ 5. Multidimensional Arrays (2D Array)
Looping through 2D array:
📌 Output:
✅ 6. Common Array Operations
| Operation | Example |
|---|---|
| Sum of elements | for (int num : numbers) sum += num; |
| Find max/min | int max = numbers[0]; then loop to compare |
| Copy array | int[] copy = Arrays.copyOf(numbers, numbers.length); |
| Sort array | Arrays.sort(numbers); |
🧠Summary
-
Arrays store fixed-size collections of same-type elements.
-
Single-dimensional arrays → List of elements.
-
Multidimensional arrays → Matrix-like structure.
-
Access using index starting from
0. -
Can loop with for or for-each.
