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 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 DimensionDescription
A list of elements of the same type, accessible through a single index.
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 DimensionsDescription
An array of arrays. Commonly used for matrices and tables.
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
Array Preview
Configure and generate your array
Java Generated Code:
// Tu código aparecerá aquí
Common Array Operations
numeros[2]
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.
for (int i = 0; i < numeros.length; i++) {
System.out.println(numeros[i]);
}
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
Result:
Implementation in Java:
// Código del algoritmo aparecerá aquí
Array vs ArrayList
Array
ArrayList
int[] numeros = new int[10];
ArrayList<Integer> numeros = new ArrayList<>();
Doesn't change after creation
Grows automatically when needed
numeros[0] = 10; // Índice específico
numeros.add(10); // Al final
Requires creating a new array
numeros.remove(0); // By index
Direct access by index O(1)
Slight overhead from being an object
Only stores the data
Stores data + metadata
Conversion between Array and ArrayList
String[] array = {"A", "B", "C"};
ArrayList<String> lista = new ArrayList<>(Arrays.asList(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
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
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.
Bubble Sort Algorithm
This is the algorithm you should imitate:
Knowledge Test
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);