DSA Tutorial
🔍

Array Basics

What Is an Array?

An array is the simplest and most fundamental data structure. It stores a collection of elements of the same type in a single, named container where every element is accessible by its position.

That position is called an index. Every array in every language starts at index 0. The first element is at index 0, the second at index 1, and so on. This 0-based convention exists because the index represents the offset from the start of the array — the first element is zero steps away from the beginning.

Three properties define every array:

  • Fixed size — the number of elements is set when the array is created and cannot change (for static arrays)
  • Same type — every element must be the same data type
  • Indexed access — any element can be retrieved directly by its index in O(1)

These three properties make arrays fast for position-based access and simple to reason about. They also create the constraints you will work around as problems grow more complex.

Declaring and Initializing Arrays

Every language has its own syntax for creating arrays. The concept is identical — reserve space for n elements of a type — but the spelling differs.

Declaration with a Fixed Size

When you know the size but not the values yet, declare an empty array and fill it later.

Java
1public class ArrayDeclaration { 2 3 public static void main(String[] args) { 4 // Declare an integer array of size 5 — values default to 0 5 int[] scores = new int[5]; 6 7 // Declare a string array of size 3 — values default to null 8 String[] names = new String[3]; 9 10 System.out.println("scores length: " + scores.length); 11 System.out.println("names length: " + names.length); 12 System.out.println("scores[0] default value: " + scores[0]); 13 } 14}
Output:
scores length: 5
names length:  3
scores[0] default value: 0

Declaration with Known Values

When you know the values upfront, initialize the array directly with a literal.

Java
1public class ArrayInitialization { 2 3 public static void main(String[] args) { 4 // Initialize with values — size is inferred from the list 5 int[] scores = {85, 92, 78, 95, 60}; 6 String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"}; 7 8 System.out.println("First score: " + scores[0]); 9 System.out.println("Last score: " + scores[scores.length - 1]); 10 System.out.println("Third day: " + days[2]); 11 } 12}
Output:
First score: 85
Last score:  60
Third day:   Wed

How Indexing Works

Every array element has exactly one index. Indices start at 0 and go up to length - 1. This is not arbitrary — it comes from how memory addresses are computed.

Array: [85, 92, 78, 95, 60]
Index:   0   1   2   3   4
         ↑               ↑
      first            last
    (index 0)    (index length-1 = 4)

To access any element: array[index]

  • scores[0] → 85 (first element)
  • scores[2] → 78 (third element)
  • scores[4] → 60 (last element, index = length - 1)

Accessing and Updating Elements

Java
1public class ArrayAccess { 2 3 public static void main(String[] args) { 4 int[] temperatures = {22, 25, 19, 27, 23}; 5 6 // Read access — O(1) 7 System.out.println("Day 1 temperature: " + temperatures[0]); 8 System.out.println("Day 3 temperature: " + temperatures[2]); 9 10 // Write access — update an element at a specific index 11 temperatures[2] = 21; // Day 3 changed 12 System.out.println("Day 3 updated: " + temperatures[2]); 13 14 // Access the last element without hardcoding the index 15 System.out.println("Last day: " + temperatures[temperatures.length - 1]); 16 } 17}
Output:
Day 1 temperature: 22
Day 3 temperature: 19
Day 3 updated:     21
Last day:          23

Array Bounds: The Most Common Beginner Error

Every array has valid indices from 0 to length - 1. Accessing any index outside this range is an out-of-bounds error. It is one of the most frequent bugs in array problems.

Array: [85, 92, 78, 95, 60]   length = 5
Valid indices: 0, 1, 2, 3, 4

scores[-1]  → out of bounds (except Python, which handles this specially)
scores[5]   → out of bounds — no element at index 5
scores[100] → out of bounds

Each language handles this differently:

LanguageWhat happens on out-of-bounds
JavaThrows ArrayIndexOutOfBoundsException at runtime
PythonRaises IndexError at runtime (negative indices are valid and wrap around)
C++Undefined behavior — may crash, may return garbage, may corrupt memory
JavaScriptReturns undefined — no error thrown

C++ is the most dangerous: it silently continues with garbage data. JavaScript is the most forgiving but hides bugs. Java and Python fail loudly, which makes bugs easier to find.

Always verify your loop boundaries before accessing array elements:

Safe access patterns:

  Accessing first element:  arr[0]              — only safe if arr.length > 0
  Accessing last element:   arr[arr.length - 1] — only safe if arr.length > 0
  Loop from start to end:   i from 0 to arr.length - 1 (inclusive)
                            i < arr.length (exclusive upper bound)

Common mistake:
  for i from 0 to arr.length (inclusive) → accesses arr[arr.length] → OUT OF BOUNDS
  
Correct:
  for i from 0 to arr.length - 1 (inclusive)
  for i from 0; i < arr.length (exclusive)

Language-Specific Array Behavior

Arrays work differently across languages in ways that affect how you use them. These differences matter in interviews when you are writing real code.

Java

Java has two distinct array types: raw arrays (int[]) and dynamic arrays (ArrayList<Integer>).

  • Raw arrays have fixed size, set at creation
  • int[] stores primitive values directly — more memory-efficient than Integer[]
  • Arrays do not resize; use ArrayList when you need dynamic growth
  • array.length is a property, not a method call (no parentheses)

Python

Python lists behave as dynamic arrays and are the standard tool for array problems.

  • No fixed size — lists grow and shrink freely
  • Supports negative indexing: list[-1] is the last element, list[-2] is second to last
  • Supports slicing: list[1:4] returns elements at indices 1, 2, 3
  • Elements can be of mixed types, though in algorithm problems they usually are not

C++

C++ has two array options: raw C-style arrays and std::vector.

  • Raw arrays (int arr[5]) have fixed size determined at compile time
  • Raw arrays do not know their own size — you must track it manually
  • std::vector<int> is the dynamic, self-aware alternative recommended for most problems
  • Raw C-style arrays in function parameters decay to pointers — be careful with sizeof

JavaScript

JavaScript arrays are dynamic objects, not fixed-size containers.

  • No type restriction — elements can be mixed types
  • array.length is writable — setting it to a smaller number truncates the array
  • Access beyond the end returns undefined, not an error
  • For algorithm problems, treat JavaScript arrays as Python lists — they behave similarly

Choosing the Right Array Type for the Problem

Before writing code, decide which type to use:

Know the exact size upfront and it will not change?
  → Use a raw array (Java int[], C++ int[])

Size is unknown or will change during processing?
  → Use a dynamic array (Java ArrayList, C++ vector, Python list, JS array)

Need fast index access above all else?
  → Either type gives O(1) — use whichever is simpler to write

Writing Python or JavaScript?
  → Always use the built-in list/array — they are already dynamic

Practical Example: Building and Reading an Array

This brings everything together — declaring, filling, and reading back an array of student grades.

Java
1public class StudentGrades { 2 3 public static void main(String[] args) { 4 // Declare an array to hold 5 student grades 5 int[] grades = new int[5]; 6 7 // Fill the array with values 8 grades[0] = 88; 9 grades[1] = 72; 10 grades[2] = 95; 11 grades[3] = 61; 12 grades[4] = 84; 13 14 // Read and display each grade with its student number 15 for (int i = 0; i < grades.length; i++) { 16 System.out.println("Student " + (i + 1) + ": " + grades[i]); 17 } 18 19 // Find passing grades (>= 70) 20 System.out.println("\nPassing students:"); 21 for (int i = 0; i < grades.length; i++) { 22 if (grades[i] >= 70) { 23 System.out.println(" Student " + (i + 1) + " passed with " + grades[i]); 24 } 25 } 26 } 27}
Output:
Student 1: 88
Student 2: 72
Student 3: 95
Student 4: 61
Student 5: 84

Passing students:
  Student 1 passed with 88
  Student 2 passed with 72
  Student 3 passed with 95
  Student 5 passed with 84

Interview Questions

Q: Why do arrays start at index 0 instead of 1?

Because the index represents the memory offset from the start of the array. The first element is at offset 0 — zero steps from the beginning. This is a hardware-level convention that all major programming languages follow. In a 0-based system, the last element is at length - 1. In a 1-based system, it would be at length. The 0-based system makes arithmetic cleaner and maps directly to memory.

Q: What is the time complexity of accessing an element by index?

O(1) — constant time regardless of array size or position. The memory address of any element is computed directly as base_address + (index × element_size). This is a single arithmetic operation — no searching, no scanning.

Q: What happens when you access an array out of bounds?

It depends on the language. Java throws ArrayIndexOutOfBoundsException. Python raises IndexError. C++ produces undefined behavior — it may crash, return garbage, or silently corrupt memory. JavaScript returns undefined. In interviews, always check that your indices are within [0, length - 1] before accessing.

Q: What is the difference between an array and a list in Python?

Python does not have a built-in fixed-size array in the same way Java and C++ do. The Python list is a dynamic array — it resizes automatically. For algorithm problems, the Python list is the standard tool. The array module provides typed fixed-size arrays but is rarely used in interviews.

FAQs

Can an array store elements of different types?

In statically typed languages (Java, C++), no — arrays are typed and all elements must be the same type. In dynamically typed languages (Python, JavaScript), yes — you can mix types, though in algorithm problems you almost never should. Mixing types in an array makes the code harder to reason about and is a sign of a design problem.

What is the difference between array.length in Java and len(array) in Python?

In Java, length is a property of the array object — no method call, no parentheses. In Python, len() is a built-in function you call with the array as an argument. In JavaScript, array.length is a property like Java. In C++, raw arrays do not have a length property — you must track the size manually or use std::vector which has .size().

How do I find the last element of an array safely?

Use arr[arr.length - 1] in Java and JavaScript. Use arr[-1] in Python (negative indexing wraps around from the end). Use arr[size - 1] in C++ where you track size manually. Always verify the array is not empty before doing this — accessing index -1 on an empty Java array or index size - 1 on a C++ array of size 0 is an out-of-bounds error.

What is the default value of array elements in Java?

Integer and floating-point types default to 0 or 0.0. Boolean defaults to false. Object references (including String) default to null. This is guaranteed by the Java specification. In C++, raw arrays of local variables are uninitialized — their values are garbage unless explicitly set.

Summary

An array stores elements of the same type in indexed slots starting at 0. Index access is O(1) — the fastest possible lookup — because the memory address is computed directly from the index.

The key ideas to carry forward:

  • Arrays are 0-indexed — valid indices run from 0 to length - 1
  • Index access and update are both O(1) — direct memory address computation
  • Out-of-bounds access is a critical bug — each language handles it differently
  • Java and C++ arrays are fixed-size; Python lists and JS arrays are dynamic
  • C++ raw arrays do not track their own size — always pass the size separately or use std::vector
  • Python negative indexing (arr[-1]) is valid and means "from the end"

In the next topic, you will explore How Arrays Work in Memory — understanding the physical layout that makes O(1) access possible and why it matters for performance.

Suggested Quiz

An array has 8 elements. What is the valid index range?

1/6
Array Basics