Arrays en Java

Learn to work with organized data collections

What is an Array?

An array is like a shelf

An array is a data structure that stores multiple values of the SAME type in contiguous memory positions.

Array of Integers

Array Characteristics:

Fixed Size

Once created, its size cannot be changed

Numeric Indices

Access elements using indices (0 to n-1)

Contiguous Memory

All elements are stored together in memory

Fast Access

Direct access to any position in constant time

Types of Arrays

One-dimensional Array

1 Dimension
Description

A list of elements of the same type, accessible through a single index.

int[] numeros = {10, 20, 30, 40, 50};
10
[0]
20
[1]
30
[2]
40
[3]
50
[4]
Declaration and Usage
Declaration:
// Tres formas de declarar arraysint[] numeros1;           // Declarationint numeros2[];           // Forma alternativaint[] numeros3 = new int[5]; // Declaración + creación
Initialization:
// Inicialización directaint[] numeros = {10, 20, 30, 40, 50};

// Inicialización por elementoint[] edades = new int[3];
edades[0] = 25;
edades[1] = 30;
edades[2] = 35;
Accessing elements:
int[] numeros = {10, 20, 30, 40, 50};
int primerElemento = numeros[0];  // 10
int ultimoElemento = numeros[4];  // 50

// Modificar elementonumeros[2] = 100;  // Cambia 30 por 100

Multidimensional Array

2 or more Dimensions
Description

An array of arrays. Commonly used for matrices and tables.

int[][] matriz = {{1, 2, 3}, {4, 5, 6}};
1
[0][0]
2
[0][1]
3
[0][2]
4
[1][0]
5
[1][1]
6
[1][2]
Usage Examples
2x3 Matrix:
// Declaración e inicializaciónint[][] matriz = {
    {1, 2, 3},  // Row 0
    {4, 5, 6}   // Row 1
};

// Accessing elementsint elemento = matriz[1][2];  // 6 (row 1, column 2)
Temperature Table:
// Temperaturas por día y horadouble[][] temperaturas = new double[7][24];

// Llenar datostemperaturas[0][8] = 22.5;   // Monday, 8am
temperaturas[2][14] = 28.3;  // Wednesday, 2pm

Array Builder

Configure your Array

5
3
3

Array Preview

int[5] miArray

Configure and generate your array

Java Generated Code:
// Tu código aparecerá aquí

Common Array Operations

Example Array:
2
Accessing:
numeros[2]
Value: 30
Accessing Elements

Array elements are accessed using their index. Indices start at 0.

int[] numeros = {10, 20, 30, 40, 50};

// Acceso por índiceint primer = numeros[0];    // 10
int tercero = numeros[2];   // 30
int ultimo = numeros[4];    // 50

// Índice fuera de rango causa error// int error = numeros[5];  // ArrayIndexOutOfBoundsException

Careful! Trying to access an index outside the range (negative or greater than/equal to the size) causes ArrayIndexOutOfBoundsException.

Array to iterate:
Step 1 i = 0
for (int i = 0; i < numeros.length; i++) {
    System.out.println(numeros[i]);
}
Output:
Iterating over Arrays

There are several ways to iterate over an array:

1. Classic for loop
int[] numeros = {10, 20, 30, 40, 50};

for (int i = 0; i < numeros.length; i++) {
    System.out.println(numeros[i]);
}
2. for-each loop
int[] numeros = {10, 20, 30, 40, 50};

for (int numero : numeros) {
    System.out.println(numero);
}
3. while loop
int[] numeros = {10, 20, 30, 40, 50};
int i = 0;

while (i < numeros.length) {
    System.out.println(numeros[i]);
    i++;
}

Array Algorithms

Sum of Elements

Calculates the sum of all elements

Maximum Element

Finds the largest value

Average

Calculates the average value

Reverse Array

Reverses the order of elements

Bubble Sort

Sorts elements from smallest to largest

Binary Search

Searches in sorted arrays

Sum of Elements

Operations: 0
Time: 0ms
10
Result:
Implementation in Java:
// Código del algoritmo aparecerá aquí

Array vs ArrayList

Array

Fixed Size
VS

ArrayList

Dynamic Size
Declaration
int[] numeros = new int[10];
ArrayList<Integer> numeros = new ArrayList<>();
Size
Fixed

Doesn't change after creation

Dynamic

Grows automatically when needed

Adding elements
Limited numeros[0] = 10; // Índice específico
Easy numeros.add(10); // Al final
Removing elements
Hard

Requires creating a new array

Easy numeros.remove(0); // By index
Performance
Faster

Direct access by index O(1)

A bit slower

Slight overhead from being an object

Memory usage
More efficient

Only stores the data

More memory

Stores data + metadata

Conversion between Array and ArrayList

Array → ArrayList
String[] array = {"A", "B", "C"};
ArrayList<String> lista = new ArrayList<>(Arrays.asList(array));
ArrayList → Array
ArrayList<String> lista = new ArrayList<>();
lista.add("X"); lista.add("Y"); lista.add("Z");
String[] array = lista.toArray(new String[0]);

Practical Exercises

Grade Calculator

Easy

Create a program that calculates a student's grade average.

Requirements:
  • Create an array of 5 grades (double)
  • Calculate the sum of all grades
  • Calculate the average
  • Show all grades and the result
Expected output:
Notas: [7.5, 8.0, 6.5, 9.0, 7.0]
Addition: 38.0
Average: 7.6
Code Editor

Run your code to see the output

Game: Sort the Array

Sort the numbers from smallest to largest

Drag the numbers to sort them correctly.

Moves: 0
Time: 00:00
Difficulty:
Array to sort:

Bubble Sort Algorithm

This is the algorithm you should imitate:

1 Compare the first element with the second
2 If they're in the wrong order, swap them
3 Repeat for each adjacent pair
4 Go back to the start and repeat until it's sorted

Knowledge Test

Question 1/10

What is the index of the first element in an array?

Summary and Resources

What you learned

  • What arrays are and how they work
  • Array declaration and initialization
  • One-dimensional and multidimensional arrays
  • Common array operations
  • Basic array algorithms
  • Differences between Array and ArrayList

Common Errors

  • ArrayIndexOutOfBoundsException
  • Forgetting to initialize the array
  • Confusing array.length with array.length()
  • Trying to change the size of an array
  • Not using Arrays.toString() to print

Practical Tips

  • Use for-each when you don't need indices
  • Arrays.sort() to sort easily
  • Arrays.copyOf() to copy arrays
  • Use ArrayList when the size is variable
  • Document complex arrays with comments

Quick Reference

Declaration
tipo[] nombre = new tipo[tamaño];
tipo[] nombre = {val1, val2, val3};
Access
elemento = array[indice];
array[indice] = nuevoValor;
Iteration
for (int i = 0; i < array.length; i++)
for (tipo elemento : array)
Utilities
Arrays.sort(array);
Arrays.toString(array);
Arrays.copyOf(array, tamaño);

Additional Resources