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:

Array length: 4

3. Looping Through an Array

Using for loop:


 

Using for-each loop:


4. Array of Objects (Strings Example)


 

📌 Output:

BMW
Audi
Tesla

5. Multidimensional Arrays (2D Array)


 

Looping through 2D array:

📌 Output:

1 2 3
4 5 6
7 8 9

6. Common Array Operations

OperationExample
Sum of elementsfor (int num : numbers) sum += num;
Find max/minint max = numbers[0]; then loop to compare
Copy arrayint[] copy = Arrays.copyOf(numbers, numbers.length);
Sort arrayArrays.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.

You may also like...