Array Introduction
Imagine a row of lockers, each with a number. You can put something in locker #3, and later retrieve it quickly. In programming, an array is exactly that – a collection of elements of the same type, stored in contiguous memory locations, accessed by an index.
Arrays are fundamental in DSA. They form the basis for many data structures like stacks, queues, and hash tables.
Properties of arrays:
- Fixed size (once created, cannot change).
- Elements are stored contiguously in memory.
- Access by index: O(1) time (constant time).
- Homogeneous: all elements are of the same data type.
Declaring and initializing arrays in Java:
// Declaration
int[] numbers; // preferred style
int numbers[]; // also valid, but less common
// Allocation (size must be specified)
numbers = new int[5]; // creates array of 5 ints, default 0
// Combined declaration and initialization
int[] primes = {2, 3, 5, 7};
String[] names = new String[]{"Alice", "Bob"};
// Accessing elements
int first = primes[0]; // 2
primes[2] = 11; // change element at index 2
int length = primes.length; // 4 (length property)
Two Minute Drill
- Array: fixed-size, contiguous memory, same type elements.
- Index starts at 0, length property gives size.
- Access by index: O(1) time.
- Default values: 0 for numeric, false for boolean, null for objects.
- Arrays are objects in Java (they have a .length field).
Need more clarification?
Drop us an email at career@quipoinfotech.com
