From a loose value to an array
So far you stored data in loose variables: an age, a name, a price. With a course’s grades, nota1, nota2, nota3… stops being an option. An array stores many values of the same type under a single name.
Loose variables
nota1nota2nota3… An array
notas String
An object over a char array
How Java lays data out in memory
1 Declare
int[] edades; Creates the variable: it is null
2 Instantiate
new int[5] Reserves the block on the Heap
3 Initialize
{ 10, 20, 30 } Sets the values
int edades[] compiles, but do not use it: it comes from C.
0 0.0 '\u0000' false null Index out of range
datos[3] = 99; ArrayIndexOutOfBoundsException
Negative index
datos[-1] = 99; ArrayIndexOutOfBoundsException
Negative size
new int[-5] NegativeArraySizeException
for
for (int i = 0; i < a.length; i++) You have the index: read and modify
for-each
for (String f : frutas) The default for reading
Backwards
for (int i = a.length - 1; i >= 0; i--) From length - 1 down to 0
The trap
n = n * 2 n is a copy: the array does not change toString · deepToString sort Sorts the original
binarySearch Needs sorted data
copyOf · copyOfRange Copy and resize
fill Fill
equals · deepEquals Compares content
stream Sum, filter, average
int[] · holds the values
String[] · holds references
Shallow copy
original[0] copia[0] "Hola mundo"a single object
datos · outer array of 3 references
[0] [1] [2] Each row is an independent object: it can have a different length.
Variable
texto Original object
"hola" Never changes
toUpperCase()
"HOLA" A new object: you must assign it
Security
Paths and credentials do not change
Concurrency
Shared across threads
hashCode
Computed only once
Reuse
It is the basis of the pool
texto = "Learning" length() = 8 · last index = 7
substring(2, 5)
Start included · end excluded
indexOf()contains()startsWith()trim()replace()toUpperCase() splitString.joinstripisBlankformatted""" A single expression
"Hola " + nombre + ", tenés " + n The compiler already optimizes it
Inside a loop
for (…) { sb.append(i).append(", "); } Here StringBuilder is a necessity
StringBuffer
Same API, synchronized and slower
1 Exercise
Palindromes
StringBuilder · equals
2 Exercise
Statistics
Sum · max · average
3 Exercise
Words
split · length()
4 Exercise
Transpose
Matrix [rows][cols]
CursoDeJava · l04_arrays_y_strings
33 exercises: arrays, matrices and String
So far you stored data in loose variables: an age, a name, a price.
With a course’s grades, nota1, nota2, nota3… stops being an option.
An array stores many values of the same type under a single name.
So far you stored data in loose variables: an age, a name, a price. With a course’s grades, nota1, nota2, nota3… stops being an option. An array stores many values of the same type under a single name.
String looks like a plain type, but it is an object built on a char array.
Both share one background: how Java lays data out in memory.
String looks like a plain type, but it is an object built on a char array. Both share one background: how Java lays data out in memory.
An array is a contiguous block of memory split into equally sized cells.
The variable lives on the Stack and only holds a reference; the data lives on the Heap.
An array is a contiguous block of memory split into equally sized cells. The variable lives on the Stack and only holds a reference; the data lives on the Heap.
Reaching a cell is arithmetic: base address + i × size.
That is why edades[0] and edades[4] cost the same: instant access.
The index starts at 0 because it measures offset, not position.
Reaching a cell is arithmetic: base address + i × size. That is why edades[0] and edades[4] cost the same: instant access. The index starts at 0 because it measures offset, not position.
Right after the block sits something else in memory: the size cannot change.
array.length is an attribute; on String, texto.length() is a method.
Right after the block sits something else in memory: the size cannot change. array.length is an attribute; on String, texto.length() is a method.
Declaring creates the variable, instantiating reserves the Heap block, initializing sets the values.
With a { } literal the compiler infers the size. Avoid the legacy int edades[] syntax.
Declaring creates the variable, instantiating reserves the Heap block, initializing sets the values. With a { } literal the compiler infers the size. Avoid the legacy int edades[] syntax.
int[] edades = new int[5]; // declare + instantiateString[] lenguajes = {"Java", "Go"}; // initializer literaldouble[] precios; // declare: it is nullprecios = new double[3]; // instantiate later With new, Java fills the block with binary zeros: it never leaves garbage.
Each type reads it its own way: 0, 0.0, the null character, false or null.
With new, Java fills the block with binary zeros: it never leaves garbage. Each type reads it its own way: 0, 0.0, the null character, false or null.
new String[3] does not give three empty strings: it gives three null.
Calling .length() on a null cell ends in NullPointerException.
new String[3] does not give three empty strings: it gives three null. Calling .length() on a null cell ends in NullPointerException.
String[] nombres = new String[3]; System.out.println(nombres[0]); // nullSystem.out.println(nombres[0].length()); // NullPointerException java NulosnullException in thread "main" java.lang.NullPointerException Index 3 or -1 on a 3-element array throws ArrayIndexOutOfBoundsException.
A negative size throws NegativeArraySizeException. All three happen at runtime.
Java checks the range on every access: the error shows up exactly where it happened.
Index 3 or -1 on a 3-element array throws ArrayIndexOutOfBoundsException. A negative size throws NegativeArraySizeException. All three happen at runtime. Java checks the range on every access: the error shows up exactly where it happened.
int[] datos = new int[3]; datos[3] = 99; // index out of rangedatos[-1] = 99; // negative indexint[] otro = new int[-5]; // negative size java ErroresArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 The classic for has the index: you can read and also modify the array.
It also walks backwards, from length - 1 down to 0.
The classic for has the index: you can read and also modify the array. It also walks backwards, from length - 1 down to 0.
String[] frutas = {"Manzana", "Banana", "Naranja"}; for (int i = 0; i < frutas.length; i++) {System.out.println(i + ": " + frutas[i]);} for (int i = frutas.length - 1; i >= 0; i--) {System.out.println(frutas[i]);} The for-each reads better and removes index errors at the root.
It is the default choice when you only need to read each element.
The for-each reads better and removes index errors at the root. It is the default choice when you only need to read each element.
String[] frutas = {"Manzana", "Banana", "Naranja"}; for (String fruta : frutas) {System.out.println("Fruta: " + fruta);} The for-each variable is a copy: n = n * 2 does not change the array.
Simple rule: to write into the array you need the index.
The for-each variable is a copy: n = n * 2 does not change the array. Simple rule: to write into the array you need the index.
int[] numeros = {1, 2, 3}; for (int n : numeros) {n = n * 2; // n es una copia}for (int i = 0; i < numeros.length; i++) {numeros[i] = numeros[i] * 2;} java Duplicar[1, 2, 3] ← después del for-each[2, 4, 6] ← después del for con índice There is no array.add: a 4-slot array dies with 4 slots.
When you need more, the only way out is to ask for a new, larger block.
There is no array.add: a 4-slot array dies with 4 slots. When you need more, the only way out is to ask for a new, larger block.
Then the elements are copied one by one: copying n elements costs n operations.
The original array is left without references and the garbage collector takes it.
That is why ArrayList doubles its capacity: it spreads the cost of copying.
Then the elements are copied one by one: copying n elements costs n operations. The original array is left without references and the garbage collector takes it. That is why ArrayList doubles its capacity: it spreads the cost of copying.
Arrays.copyOf(a, n) copies with another size; copyOfRange copies a range excluding the end.
System.arraycopy gives full control over source and destination.
Arrays.copyOf(a, n) copies with another size; copyOfRange copies a range excluding the end. System.arraycopy gives full control over source and destination.
int[] datos = {10, 20, 30, 40}; int[] masGrande = Arrays.copyOf(datos, 8);int[] medio = Arrays.copyOfRange(datos, 1, 3); // [20, 30] int[] destino = new int[8];System.arraycopy(datos, 0, destino, 0, datos.length); A primitive array holds the values: new int[3] is three zeros.
An object array holds references: new String[3] is three null.
A primitive array holds the values: new int[3] is three zeros. An object array holds references: new String[3] is three null.
int[] numeros = new int[3]; // 3 cells holding 0String[] nombres = new String[3]; // 3 cells holding null The objects live elsewhere on the Heap; the array only stores their addresses.
So nombres[0].length() fails with NullPointerException until you fill it.
The objects live elsewhere on the Heap; the array only stores their addresses. So nombres[0].length() fails with NullPointerException until you fill it.
java Referencias0nullException in thread "main" java.lang.NullPointerException Arrays.copyOf makes a shallow copy: it duplicates the array, not the objects.
Both arrays point to the same object: changing one changes the other.
It never happens with String: it is immutable, sharing the reference does no harm.
Arrays.copyOf makes a shallow copy: it duplicates the array, not the objects. Both arrays point to the same object: changing one changes the other. It never happens with String: it is immutable, sharing the reference does no harm.
StringBuilder[] original = { new StringBuilder("Hello") };StringBuilder[] copia = Arrays.copyOf(original, 1); copia[0].append(" world"); System.out.println(original[0]); // "Hello world" Java has no matrices: it has an array whose elements are arrays.
Each row is an independent object with its own length.
Java has no matrices: it has an array whose elements are arrays. Each row is an independent object with its own length.
int[][] tablero = {{1, 2, 3},{4, 5, 6},{7, 8, 9}}; for (int[] fila : tablero) {for (int valor : fila) {System.out.print(valor + " ");}} A jagged array is created with new int[3][]: rows stay null until you assign them.
That is why the inner loop uses tablero[fila].length, not tablero[0].length.
A jagged array is created with new int[3][]: rows stay null until you assign them. That is why the inner loop uses tablero[fila].length, not tablero[0].length.
int[][] datos = new int[3][]; // filas en nulldatos[0] = new int[]{1, 2, 3};datos[1] = new int[]{4, 5, 6, 7, 8};datos[2] = new int[]{9, 0}; System.out.println(datos[1].length); // 5 Arrays.toString only sees the outer array: it prints the rows’ addresses.
To print a whole matrix use Arrays.deepToString.
Arrays.toString only sees the outer array: it prints the rows’ addresses. To print a whole matrix use Arrays.deepToString.
System.out.println(Arrays.toString(datos));System.out.println(Arrays.deepToString(datos)); java Imprimir[[I@1b6d3586, [I@4554617c, [I@74a14482][[1, 2, 3], [4, 5, 6, 7, 8], [9, 0]] java.util.Arrays already solves almost everything: print, sort, search, copy, fill and compare.
Arrays.stream lets you sum, filter and average without writing a loop.
java.util.Arrays already solves almost everything: print, sort, search, copy, fill and compare. Arrays.stream lets you sum, filter and average without writing a loop.
Arrays.sort sorts the original array, without creating a new one.
binarySearch searches fast, but it requires an already sorted array.
Arrays.sort sorts the original array, without creating a new one. binarySearch searches fast, but it requires an already sorted array.
int[] numeros = {42, 12, 89, 7, 23}; Arrays.sort(numeros);int indice = Arrays.binarySearch(numeros, 23); System.out.println(Arrays.toString(numeros));System.out.println("Index of 23: " + indice); java Herramientas[7, 12, 23, 42, 89]Index of 23: 2 == compares references: two arrays with the same content give false.
a.equals(b) does not help: an array does not override equals. Use Arrays.equals.
== compares references: two arrays with the same content give false. a.equals(b) does not help: an array does not override equals. Use Arrays.equals.
int[] a = {1, 2, 3};int[] b = {1, 2, 3}; System.out.println(a == b);System.out.println(a.equals(b));System.out.println(Arrays.equals(a, b)); java Compararfalsefalsetrue binarySearch on an unsorted array throws no exception: it silently returns garbage.
Sort first with Arrays.sort and only then search.
binarySearch on an unsorted array throws no exception: it silently returns garbage. Sort first with Arrays.sort and only then search.
A String is an object whose content never changes once created.
No method modifies it: toUpperCase() returns a new string.
A String is an object whose content never changes once created. No method modifies it: toUpperCase() returns a new string.
Forgetting to assign the result is mistake number one: the program carries on with the old value.
texto.toUpperCase(); is discarded; mayus = texto.toUpperCase(); keeps it.
Forgetting to assign the result is mistake number one: the program carries on with the old value. texto.toUpperCase(); is discarded; mayus = texto.toUpperCase(); keeps it.
String texto = "hola";texto.toUpperCase(); // se descartaSystem.out.println(texto); String mayus = texto.toUpperCase(); // así síSystem.out.println(mayus); java InmutableholaHOLA It is no whim: security, concurrency, cached hash and reuse.
Since nobody can modify them, the JVM shares one object among variables: that is the pool.
It is no whim: security, concurrency, cached hash and reuse. Since nobody can modify them, the JVM shares one object among variables: that is the pool.
To avoid duplicating strings, the JVM keeps literals in the String Constant Pool.
That is why s1 and s2 point to the same object and s1 == s2 is true.
To avoid duplicating strings, the JVM keeps literals in the String Constant Pool. That is why s1 and s2 point to the same object and s1 == s2 is true.
new String("Java") always creates a separate object, outside the pool.
That is why s1 == s3 is false, even though the text is the same.
new String("Java") always creates a separate object, outside the pool. That is why s1 == s3 is false, even though the text is the same.
== compares object identity; .equals() compares the content.
Golden rule: to compare text, always use .equals().
With the literal on the left you avoid NullPointerException: "exit".equals(input).
== compares object identity; .equals() compares the content. Golden rule: to compare text, always use .equals(). With the literal on the left you avoid NullPointerException: "exit".equals(input).
If the string is built at runtime, like part + "va", it is a new object.
Same text, another object: == is false and .equals() is true.
If the string is built at runtime, like part + "va", it is a new object. Same text, another object: == is false and .equals() is true.
A String is indexed just like an array: from 0 to length() - 1.
charAt(i) returns the character at position i.
A String is indexed just like an array: from 0 to length() - 1. charAt(i) returns the character at position i.
String texto = "Learning"; System.out.println(texto.length()); // 8System.out.println(texto.charAt(0)); // LSystem.out.println(texto.charAt(7)); // g substring(2, 5) cuts from index 2 up to 4: the end is not included.
Start included, end excluded: the same convention as copyOfRange and subList.
substring(2, 5) cuts from index 2 up to 4: the end is not included. Start included, end excluded: the same convention as copyOfRange and subList.
String texto = "Learning"; String parte = texto.substring(2, 5);System.out.println(parte); // "arn" With indexOf, contains, trim, replace and toUpperCase you work the text without walking it by hand.
All of them return a new string: you must assign the result.
With indexOf, contains, trim, replace and toUpperCase you work the text without walking it by hand. All of them return a new string: you must assign the result.
String texto = " Aprendiendo Java en 2026 "; texto.trim(); // sin espacios en los extremostexto.contains("Java"); // truetexto.indexOf("Java"); // 14texto.replace("2026", "2027");texto.toUpperCase(); split breaks a string into a String[] and String.join joins it back.
strip() and isBlank() are the modern version of trim() and isEmpty().
formatted controls decimals and text blocks avoid escapes.
split breaks a string into a String[] and String.join joins it back. strip() and isBlank() are the modern version of trim() and isEmpty(). formatted controls decimals and text blocks avoid escapes.
String[] provincias = "Neuquén,Córdoba,Salta".split(",");String unidas = String.join(" | ", provincias); " ".isBlank(); // true" ".isEmpty(); // false "Average %.2f".formatted(8.457); Each += on a String creates a new object and copies everything accumulated.
Over 1000 iterations that is 1000 temporary objects and half a million characters copied.
StringBuilder writes into a single buffer and only copies when it runs out of capacity.
Each += on a String creates a new object and copies everything accumulated. Over 1000 iterations that is 1000 temporary objects and half a million characters copied. StringBuilder writes into a single buffer and only copies when it runs out of capacity.
append, insert, replace, deleteCharAt and reverse modify the same object.
Each method returns the same StringBuilder: that is why they chain.
append, insert, replace, deleteCharAt and reverse modify the same object. Each method returns the same StringBuilder: that is why they chain.
StringBuilder sb = new StringBuilder("Hello"); sb.append(" world"); // "Hello world"sb.insert(0, ">> "); // ">> Hello world"sb.deleteCharAt(0); // "> Hello world"sb.reverse(); String frase = sb.toString(); In a single expression the compiler already optimizes concatenation: no StringBuilder needed.
Inside a long loop, StringBuilder is a necessity, not a preference.
StringBuffer is the same but synchronized and slower: use StringBuilder.
In a single expression the compiler already optimizes concatenation: no StringBuilder needed. Inside a long loop, StringBuilder is a necessity, not a preference. StringBuffer is the same but synchronized and slower: use StringBuilder.
Mixing up array.length and texto.length(): one is an attribute, the other a method.
Comparing strings with ==, forgetting to assign the result or looping up to <= length.
Mixing up array.length and texto.length(): one is an attribute, the other a method. Comparing strings with ==, forgetting to assign the result or looping up to <= length.
Using binarySearch without sorting or expecting copyOf to clone the objects.
Printing a matrix with toString or walking a freshly created String[] without filling it.
And concatenating inside a long loop: that is where StringBuilder goes.
Using binarySearch without sorting or expecting copyOf to clone the objects. Printing a matrix with toString or walking a freshly created String[] without filling it. And concatenating inside a long loop: that is where StringBuilder goes.
Exercise 1: a palindrome ignores spaces and case and reads the same both ways.
Normalize, reverse with StringBuilder and compare with .equals().
Exercise 1: a palindrome ignores spaces and case and reads the same both ways. Normalize, reverse with StringBuilder and compare with .equals().
String limpio = texto.replace(" ", "").toLowerCase();String reves = new StringBuilder(limpio).reverse().toString(); return limpio.equals(reves); Exercise 2: array statistics: sum, maximum, minimum and average.
A single pass is enough, or Arrays.stream with no loops.
Exercise 2: array statistics: sum, maximum, minimum and average. A single pass is enough, or Arrays.stream with no loops.
int[] datos = {42, 12, 89, 7, 23}; int max = datos[0];int suma = 0;for (int n : datos) {if (n > max) max = n;suma += n;}double promedio = (double) suma / datos.length; Exercise 3: count words and find the longest one with split.
You walk the String[] keeping the longest one seen.
Exercise 3: count words and find the longest one with split. You walk the String[] keeping the longest one seen.
String[] palabras = texto.strip().split("\\s+"); String masLarga = palabras[0];for (String p : palabras) {if (p.length() > masLarga.length()) masLarga = p;} Exercise 4: transposing a matrix swaps rows and columns.
The result is columns × rows and is filled with t[c][f] = m[f][c].
Exercise 4: transposing a matrix swaps rows and columns. The result is columns × rows and is filled with t[c][f] = m[f][c].
int[][] t = new int[cols][filas]; for (int f = 0; f < filas; f++) {for (int c = 0; c < cols; c++) {t[c][f] = m[f][c];}} Contiguous, fixed, from 0: the array rules come from memory.
String is immutable, == compares identity and .equals() the content.
And StringBuilder when you concatenate inside a loop.
Contiguous, fixed, from 0: the array rules come from memory. String is immutable, == compares identity and .equals() the content. And StringBuilder when you concatenate inside a loop.
Reinforce everything with 33 exercises in the course repository.
Clone it, open l04_arrays_y_strings and run each program while you reread the lesson.
Reinforce everything with 33 exercises in the course repository. Clone it, open l04_arrays_y_strings and run each program while you reread the lesson.