Arrays and Strings, step by step

Loose variables

nota1nota2nota3…

An array

807192103
notas

String

J0a1v2a3

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.

byte · short · int · long 0
float · double 0.0
char '\u0000'
boolean false
References (String, objects) 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

102132
n = n * 2 n is a copy: the array does not change
toString · deepToString

Print

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

000102

String[] · holds references

null0null1null2

Shallow copy

original[0] copia[0]
"Hola mundo"

a single object

datos · outer array of 3 references

[0]
102132
length 3
[1]
4051627384
length 5
[2]
9001
length 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"
L0e1a2r3n4i5n6g7

length() = 8 · last index = 7

substring(2, 5)

a2r3n4

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

length vs length()Comparing with ==Forgetting to assignLooping up to <= lengthConcatenating in a loopbinarySearch unsortedcopyOf does not clone objectstoString on a matrixNew String[] = nulls

1 Exercise

Palindromes

StringBuilder · equals

2 Exercise

Statistics

Sum · max · average

3 Exercise

Words

split · length()

4 Exercise

Transpose

Matrix [rows][cols]

1 · Contiguous block2 · length vs length()3 · Growing = copying4 · References: shallow copy5 · Matrix = array of arrays6 · Arrays solves almost all7 · String is immutable8 · Pool and .equals()9 · StringBuilder in loops

CursoDeJava · l04_arrays_y_strings

33 exercises: arrays, matrices and String