Definições e Conceitos Fundamentais
Um vetor (ou array unidimensional) é um conjunto de números organizados em uma fileira ou coluna. Todos os elementos do vetor são do mesmo tipo (int, double, String, etc.).
Vetor = Conjunto de valores em sequência, armazenados em uma única variável.
Cada elemento pode ser acessado através de um índice (começando em 0).
public class VetorInteiros {
public static void main(String[] args) {
// Definindo um vetor de 5 números inteiros
int[] numeros = {10, 20, 30, 40, 50};
// Exibindo os elementos
System.out.println("Vetor de inteiros:");
for (int i = 0; i < numeros.length; i++) {
System.out.println("Índice " + i + ": " + numeros[i]);
}
}
}
Vetor de inteiros:
Índice 0: 10
Índice 1: 20
Índice 2: 30
Índice 3: 40
Índice 4: 50
public class VetorDecimais {
public static void main(String[] args) {
// Definindo um vetor de números decimais
double[] precos = {19.99, 45.50, 12.30, 67.80};
System.out.println("Vetor de preços:");
for (int i = 0; i < precos.length; i++) {
System.out.printf("Índice %d: R$ %.2f\n", i, precos[i]);
}
}
}
Vetor de preços:
Índice 0: R$ 19.99
Índice 1: R$ 45.50
Índice 2: R$ 12.30
Índice 3: R$ 67.80
public class ConstruirVetor {
public static void main(String[] args) {
// Criando um vetor vazio de 10 posições
int[] vetor = new int[10];
// Preenchendo o vetor usando loop for
for (int i = 0; i < vetor.length; i++) {
vetor[i] = i * 2; // 0, 2, 4, 6, 8...
}
// Exibindo o vetor
System.out.println("Vetor construído com loop:");
for (int i = 0; i < vetor.length; i++) {
System.out.println("vetor[" + i + "] = " + vetor[i]);
}
}
}
Vetor construído com loop:
vetor[0] = 0
vetor[1] = 2
vetor[2] = 4
vetor[3] = 6
vetor[4] = 8
vetor[5] = 10
vetor[6] = 12
vetor[7] = 14
vetor[8] = 16
vetor[9] = 18
O índice é a posição de cada elemento no vetor. Em Java, o primeiro elemento sempre tem índice 0.
| Índice | 0 | 1 | 2 | 3 | 4 |
| Valor | 100 | 200 | 300 | 400 | 500 |
Importante: Se um vetor tem 5 elementos, os índices são 0, 1, 2, 3, 4 (não de 1 a 5!).
Último índice: vetor.length - 1
Uma matriz (ou array bidimensional) é um conjunto de vetores organizados em linhas e colunas. É como uma tabela onde cada célula pode armazenar um valor.
Matriz = Conjunto de vetores (linhas e colunas)
Acesso: matriz[linha][coluna]
public class MatrizInteiros {
public static void main(String[] args) {
// Definindo uma matriz 3x3 de inteiros
int[][] matriz = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Exibindo a matriz
System.out.println("Matriz 3x3:");
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[i].length; j++) {
System.out.print(matriz[i][j] + "\t");
}
System.out.println();
}
}
}
Matriz 3x3:
1 2 3
4 5 6
7 8 9
public class MatrizDecimais {
public static void main(String[] args) {
// Matriz 2x3 de notas
double[][] notas = {
{7.5, 8.0, 9.2},
{6.8, 7.9, 8.5}
};
System.out.println("Matriz de notas:");
for (int i = 0; i < notas.length; i++) {
System.out.print("Aluno " + (i + 1) + ": ");
for (int j = 0; j < notas[i].length; j++) {
System.out.print(notas[i][j] + " ");
}
System.out.println();
}
}
}
Matriz de notas:
Aluno 1: 7.5 8.0 9.2
Aluno 2: 6.8 7.9 8.5
Para acessar um elemento de uma matriz, usamos dois índices:
public class AcessoMatriz {
public static void main(String[] args) {
int[][] matriz = {
{10, 20, 30},
{40, 50, 60}
};
// Acessando elementos específicos
System.out.println("Elemento [0][0]: " + matriz[0][0]); // 10
System.out.println("Elemento [0][1]: " + matriz[0][1]); // 20
System.out.println("Elemento [1][0]: " + matriz[1][0]); // 40
System.out.println("Elemento [1][2]: " + matriz[1][2]); // 60
// Dimensões da matriz
System.out.println("\nNúmero de linhas: " + matriz.length);
System.out.println("Número de colunas: " + matriz[0].length);
}
}
Elemento [0][0]: 10
Elemento [0][1]: 20
Elemento [1][0]: 40
Elemento [1][2]: 60
Número de linhas: 2
Número de colunas: 3
Um vetor pode representar uma linha de pixels em uma imagem em tons de cinza:
public class VetorTonsCinza {
public static void main(String[] args) {
// Vetor representando intensidades de pixels
int[] linha = new int[8];
// Preenchendo com valores de 0 a 224 (passo de 32)
for (int i = 0; i < linha.length; i++) {
linha[i] = i * 32;
}
// Exibindo o vetor
System.out.println("Vetor de tons de cinza:");
for (int i = 0; i < linha.length; i++) {
System.out.println("Pixel " + i + ": intensidade " + linha[i]);
}
}
}
Vetor de tons de cinza:
Pixel 0: intensidade 0
Pixel 1: intensidade 32
Pixel 2: intensidade 64
Pixel 3: intensidade 96
Pixel 4: intensidade 128
Pixel 5: intensidade 160
Pixel 6: intensidade 192
Pixel 7: intensidade 224
| Característica | Vetor (Array 1D) | Matriz (Array 2D) |
|---|---|---|
| Dimensão | 1D (unidimensional) | 2D (bidimensional) |
| Estrutura | Linha ou coluna | Linhas e colunas (tabela) |
| Declaração | int[] vetor |
int[][] matriz |
| Acesso | vetor[i] |
matriz[i][j] |
| Tamanho | vetor.length |
matriz.length (linhas)matriz[0].length (colunas) |
| Exemplo | [10, 20, 30, 40] | [[1, 2], [3, 4]] |
public class ConstruirMatriz {
public static void main(String[] args) {
// Criando matriz 4x5 vazia
int[][] matriz = new int[4][5];
// Preenchendo com valores usando loop aninhado
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[i].length; j++) {
matriz[i][j] = (i + 1) * (j + 1);
}
}
// Exibindo a matriz (tabuada)
System.out.println("Matriz 4x5 (mini tabuada):");
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[i].length; j++) {
System.out.print(matriz[i][j] + "\t");
}
System.out.println();
}
}
}
Matriz 4x5 (mini tabuada):
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
public class AnaliseDados {
public static void main(String[] args) {
// Vetor com vendas da semana
double[] vendas = {1500.50, 2300.75, 1800.00, 2100.30, 2500.00};
// Calculando total e média
double total = 0;
for (int i = 0; i < vendas.length; i++) {
total += vendas[i];
}
double media = total / vendas.length;
System.out.println("=== ANÁLISE DE VENDAS ===");
System.out.println("Total de vendas: R$ " + total);
System.out.println("Média diária: R$ " + media);
// Encontrando maior e menor venda
double maior = vendas[0];
double menor = vendas[0];
for (int i = 1; i < vendas.length; i++) {
if (vendas[i] > maior) {
maior = vendas[i];
}
if (vendas[i] < menor) {
menor = vendas[i];
}
}
System.out.println("Maior venda: R$ " + maior);
System.out.println("Menor venda: R$ " + menor);
}
}
=== ANÁLISE DE VENDAS ===
Total de vendas: R$ 10200.55
Média diária: R$ 2040.11
Maior venda: R$ 2500.0
Menor venda: R$ 1500.5
Teste seus conhecimentos sobre Vetores e Matrizes:
int[] vetor ou double[] vetorvetor[i]vetor.lengthvetor.length - 1int[][] matriz ou double[][] matrizmatriz[i][j]matriz.lengthmatriz[0].lengthmatriz[0][0]Reforce o conteúdo desta aula com mais dois exercícios práticos: