Arrays in Java
An array is a container that holds a fixed number of values of a single type. It's like a row of lockers, each with an index. Arrays are fundamental for DSA – they form the basis for many algorithms.
Declaring and Initializing Arrays
// Declaration
int[] numbers; // preferred
int numbers[]; // also valid
// Initialization with size
numbers = new int[5]; // default values 0
// Declare and initialize together
int[] primes = {2, 3, 5, 7};
Accessing Elements
Use index from 0 to length-1.
int first = primes[0]; // 2
primes[2] = 11; // change element at index 2
int len = primes.length; // length property
Multi-Dimensional Arrays
Arrays of arrays (like matrices).
int[][] matrix = {
{1, 2},
{3, 4}
};
int val = matrix[0][1]; // 2
Two Minute Drill
- Arrays store fixed-size, same-type elements.
- Index starts at 0, length property gives size.
- Can be 1D or multi-dimensional.
- Arrays are objects; null if not initialized.
- Used as building blocks for lists, stacks, etc.
Need more clarification?
Drop us an email at career@quipoinfotech.com
