0%
Core Java: Guia Completo para Dominar os Fundamentos

Core Java: Guia Completo para Dominar os Fundamentos

Um guia detalhado dos conceitos fundamentais do Java, das estruturas básicas à programação orientada a objetos, com exemplos práticos para todos os níveis.

I

InSkillCoach

· min

Core Java: Guia Completo para Dominar os Fundamentos

Java é uma das linguagens de programação mais utilizadas no mundo, especialmente apreciada por sua portabilidade, robustez e seu rico ecossistema. Este guia apresenta os conceitos fundamentais do Core Java, desde o básico até os recursos mais avançados.

Introdução ao Java

Java foi criado por James Gosling na Sun Microsystems (hoje Oracle) e lançado em 1995. Sua filosofia “Write Once, Run Anywhere” (WORA) revolucionou o desenvolvimento de software.

Principais características

  • Orientado a objetos: Tudo em Java é um objeto, com exceção dos tipos primitivos
  • Independente de plataforma: Graças à JVM (Java Virtual Machine)
  • Robusto: Tratamento de erros sólido, verificação de tipos em tempo de compilação
  • Seguro: Execução em um ambiente controlado (sandbox)
  • Multithreading: Suporte nativo à programação concorrente
  • Alto desempenho: Compilador JIT (Just-In-Time) que otimiza a execução

Instalação e configuração

Instalar o JDK (Java Development Kit)

# Sur Ubuntu/Debian
sudo apt update
sudo apt install openjdk-17-jdk

# Sur macOS avec Homebrew
brew install openjdk@17

# Sur Windows
# Télécharger depuis https://www.oracle.com/java/technologies/downloads/

Configurar as variáveis de ambiente

# Sur Linux/macOS
export JAVA_HOME=/path/to/jdk
export PATH=$PATH:$JAVA_HOME/bin

# Sur Windows
# Définir JAVA_HOME et ajouter %JAVA_HOME%\bin au PATH

Primeiros passos com Java

Estrutura básica de um programa Java

// Fichier: HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Compilar e executar

# Compiler
javac HelloWorld.java

# Exécuter
java HelloWorld

Tipos de dados e variáveis

Tipos primitivos

// Types numériques entiers
byte b = 127;         // 8 bits, -128 à 127
short s = 32767;      // 16 bits, -32,768 à 32,767
int i = 2147483647;   // 32 bits, -2,147,483,648 à 2,147,483,647
long l = 9223372036854775807L; // 64 bits, très grand intervalle

// Types numériques à virgule flottante
float f = 3.14f;      // 32 bits
double d = 3.14159;   // 64 bits

// Autres types primitifs
char c = 'A';         // 16 bits, caractère Unicode
boolean bool = true;  // true ou false

Variáveis e constantes

// Déclaration de variable
int nombre;
nombre = 42;

// Déclaration et initialisation
String message = "Bonjour";

// Constantes (final)
final double PI = 3.14159;

Operadores

Operadores aritméticos

int a = 10, b = 3;
int somme = a + b;       // 13
int difference = a - b;  // 7
int produit = a * b;     // 30
int quotient = a / b;    // 3 (division entière)
int reste = a % b;       // 1 (modulo)

// Incrémentation et décrémentation
a++;  // a = a + 1
b--;  // b = b - 1

Operadores de comparação

boolean egal = (a == b);        // false
boolean different = (a != b);   // true
boolean superieur = (a > b);    // true
boolean inferieur = (a < b);    // false
boolean supOuEgal = (a >= b);   // true
boolean infOuEgal = (a <= b);   // false

Operadores lógicos

boolean x = true, y = false;
boolean et = x && y;    // false (AND logique)
boolean ou = x || y;    // true (OR logique)
boolean non = !x;       // false (NOT logique)

Estruturas de controle

Condições

// If-else
int age = 18;
if (age < 18) {
    System.out.println("Mineur");
} else if (age == 18) {
    System.out.println("Tout juste majeur");
} else {
    System.out.println("Majeur");
}

// Switch
int jour = 3;
switch (jour) {
    case 1:
        System.out.println("Lundi");
        break;
    case 2:
        System.out.println("Mardi");
        break;
    case 3:
        System.out.println("Mercredi");
        break;
    // ...
    default:
        System.out.println("Jour inconnu");
}

// Expression ternaire
String statut = (age >= 18) ? "Majeur" : "Mineur";

Laços de repetição

// Boucle for
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

// Boucle while
int compteur = 0;
while (compteur < 5) {
    System.out.println(compteur);
    compteur++;
}

// Boucle do-while
int j = 0;
do {
    System.out.println(j);
    j++;
} while (j < 5);

// Boucle for-each (pour les collections)
int[] nombres = {1, 2, 3, 4, 5};
for (int nombre : nombres) {
    System.out.println(nombre);
}

Arrays e Collections

Arrays

// Déclaration et initialisation d'un tableau
int[] nombres = new int[5];
nombres[0] = 10;
nombres[1] = 20;

// Initialisation avec des valeurs
int[] valeurs = {10, 20, 30, 40, 50};

// Tableau multidimensionnel
int[][] matrice = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Parcourir un tableau
for (int i = 0; i < nombres.length; i++) {
    System.out.println(nombres[i]);
}

Collections Framework

import java.util.*;

// Liste
List<String> liste = new ArrayList<>();
liste.add("Pomme");
liste.add("Banane");
liste.add("Orange");
System.out.println(liste.get(1));  // Banane
liste.remove("Pomme");

// Ensemble (éléments uniques)
Set<Integer> ensemble = new HashSet<>();
ensemble.add(1);
ensemble.add(2);
ensemble.add(1);  // Ignoré car déjà présent
System.out.println(ensemble.size());  // 2

// Map (clé-valeur)
Map<String, Integer> map = new HashMap<>();
map.put("Pierre", 30);
map.put("Marie", 25);
System.out.println(map.get("Marie"));  // 25

Programação Orientada a Objetos (POO)

Classes e objetos

// Définition d'une classe
public class Personne {
    // Attributs (champs)
    private String nom;
    private int age;
    
    // Constructeur
    public Personne(String nom, int age) {
        this.nom = nom;
        this.age = age;
    }
    
    // Méthodes
    public void sePresenter() {
        System.out.println("Je m'appelle " + nom + " et j'ai " + age + " ans.");
    }
    
    // Getters et Setters
    public String getNom() {
        return nom;
    }
    
    public void setNom(String nom) {
        this.nom = nom;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
}

// Utilisation de la classe
Personne personne = new Personne("Alice", 30);
personne.sePresenter();
personne.setAge(31);
System.out.println(personne.getAge());  // 31

Herança

// Classe parente
public class Animal {
    protected String nom;
    
    public Animal(String nom) {
        this.nom = nom;
    }
    
    public void manger() {
        System.out.println(nom + " mange.");
    }
}

// Classe enfant
public class Chien extends Animal {
    private String race;
    
    public Chien(String nom, String race) {
        super(nom);  // Appel du constructeur parent
        this.race = race;
    }
    
    public void aboyer() {
        System.out.println(nom + " aboie.");
    }
    
    // Surcharge de méthode
    @Override
    public void manger() {
        System.out.println(nom + " le chien mange des croquettes.");
    }
}

// Utilisation
Chien rex = new Chien("Rex", "Berger Allemand");
rex.manger();  // "Rex le chien mange des croquettes."
rex.aboyer();  // "Rex aboie."

Polimorfismo

Animal animal1 = new Animal("Truc");
Animal animal2 = new Chien("Médor", "Labrador");  // Polymorphisme

animal1.manger();  // "Truc mange."
animal2.manger();  // "Médor le chien mange des croquettes."

// animal2.aboyer();  // Erreur de compilation, car animal2 est de type Animal
((Chien) animal2).aboyer();  // OK après cast

Interfaces

// Définition d'une interface
public interface Nageur {
    void nager();
}

// Implémentation d'une interface
public class Poisson extends Animal implements Nageur {
    public Poisson(String nom) {
        super(nom);
    }
    
    @Override
    public void nager() {
        System.out.println(nom + " nage rapidement.");
    }
}

// Multiple implémentation
public class Canard extends Animal implements Nageur {
    public Canard(String nom) {
        super(nom);
    }
    
    @Override
    public void nager() {
        System.out.println(nom + " nage lentement.");
    }
}

// Utilisation
Nageur nageur1 = new Poisson("Nemo");
Nageur nageur2 = new Canard("Donald");
nageur1.nager();  // "Nemo nage rapidement."
nageur2.nager();  // "Donald nage lentement."

Classes abstratas

// Classe abstraite
public abstract class Vehicule {
    protected String marque;
    
    public Vehicule(String marque) {
        this.marque = marque;
    }
    
    // Méthode concrète
    public void demarrer() {
        System.out.println("Le véhicule démarre.");
    }
    
    // Méthode abstraite (à implémenter par les sous-classes)
    public abstract void accelerer();
}

// Implémentation d'une classe abstraite
public class Voiture extends Vehicule {
    public Voiture(String marque) {
        super(marque);
    }
    
    @Override
    public void accelerer() {
        System.out.println("La voiture " + marque + " accélère.");
    }
}

Tratamento de exceções

Try-catch-finally

try {
    // Code susceptible de générer une exception
    int resultat = 10 / 0;  // Division par zéro
} catch (ArithmeticException e) {
    // Gestion de l'exception
    System.out.println("Erreur: Division par zéro");
    e.printStackTrace();
} finally {
    // Code exécuté dans tous les cas
    System.out.println("Fin du traitement");
}

Exceções personalizadas

// Définition d'une exception personnalisée
public class AgeInvalideException extends Exception {
    public AgeInvalideException(String message) {
        super(message);
    }
}

// Utilisation
public class Utilisateur {
    private String nom;
    private int age;
    
    public void setAge(int age) throws AgeInvalideException {
        if (age < 0 || age > 150) {
            throw new AgeInvalideException("L'âge doit être compris entre 0 et 150");
        }
        this.age = age;
    }
}

// Gestion de l'exception
Utilisateur utilisateur = new Utilisateur();
try {
    utilisateur.setAge(200);
} catch (AgeInvalideException e) {
    System.out.println("Erreur: " + e.getMessage());
}

Entrada/Saída (I/O)

Leitura de arquivos

import java.io.*;

// try-with-resources pour fermeture automatique
try (BufferedReader reader = new BufferedReader(new FileReader("fichier.txt"))) {
    String ligne;
    while ((ligne = reader.readLine()) != null) {
        System.out.println(ligne);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Escrita de arquivos

try (BufferedWriter writer = new BufferedWriter(new FileWriter("sortie.txt"))) {
    writer.write("Ligne 1");
    writer.newLine();
    writer.write("Ligne 2");
} catch (IOException e) {
    e.printStackTrace();
}

Fluxos de E/S

// Entrée console
try (Scanner scanner = new Scanner(System.in)) {
    System.out.print("Entrez votre nom: ");
    String nom = scanner.nextLine();
    System.out.println("Bonjour, " + nom + "!");
}

// Sortie formatée
System.out.printf("Température: %.1f°C%n", 22.5);

Generics

// Classe générique
public class Boite<T> {
    private T contenu;
    
    public void mettre(T contenu) {
        this.contenu = contenu;
    }
    
    public T prendre() {
        return contenu;
    }
}

// Utilisation
Boite<String> boiteTexte = new Boite<>();
boiteTexte.mettre("Hello");
String texte = boiteTexte.prendre();

Boite<Integer> boiteNombre = new Boite<>();
boiteNombre.mettre(42);
int nombre = boiteNombre.prendre();

Métodos genéricos

public <T> void afficherTableau(T[] tableau) {
    for (T element : tableau) {
        System.out.println(element);
    }
}

// Utilisation
String[] mots = {"Bonjour", "le", "monde"};
Integer[] nombres = {1, 2, 3, 4, 5};

afficherTableau(mots);
afficherTableau(nombres);

Lambda e Streams (Java 8+)

Expressões lambda

// Interface fonctionnelle
interface Calculateur {
    int calculer(int a, int b);
}

// Approche traditionnelle
Calculateur addition = new Calculateur() {
    @Override
    public int calculer(int a, int b) {
        return a + b;
    }
};

// Avec lambda
Calculateur additionLambda = (a, b) -> a + b;
System.out.println(additionLambda.calculer(5, 3));  // 8

// Autres exemples
Runnable tache = () -> System.out.println("Tâche exécutée");
Comparator<String> comparateur = (s1, s2) -> s1.length() - s2.length();

API Stream

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

List<String> noms = Arrays.asList("Jean", "Marie", "Pierre", "Sophie");

// Filtrage
List<String> nomsLongs = noms.stream()
    .filter(nom -> nom.length() > 4)
    .collect(Collectors.toList());  // [Marie, Pierre, Sophie]

// Mapping
List<Integer> longueurs = noms.stream()
    .map(String::length)
    .collect(Collectors.toList());  // [4, 5, 6, 6]

// Réduction
int somme = noms.stream()
    .mapToInt(String::length)
    .sum();  // 21

// Autres opérations
boolean tousLongs = noms.stream().allMatch(nom -> nom.length() > 3);  // true
String concatenation = noms.stream().collect(Collectors.joining(", "));  // "Jean, Marie, Pierre, Sophie"

Multithreading e concorrência

Criação de threads

// Méthode 1: Étendre Thread
class MonThread extends Thread {
    @Override
    public void run() {
        System.out.println("MonThread s'exécute");
    }
}

// Méthode 2: Implémenter Runnable
class MaTache implements Runnable {
    @Override
    public void run() {
        System.out.println("MaTache s'exécute");
    }
}

// Utilisation
Thread thread1 = new MonThread();
thread1.start();

Thread thread2 = new Thread(new MaTache());
thread2.start();

// Lambda avec Runnable
Thread thread3 = new Thread(() -> {
    System.out.println("Tâche lambda s'exécute");
});
thread3.start();

Sincronização

public class Compteur {
    private int valeur = 0;
    
    // Méthode synchronisée
    public synchronized void incrementer() {
        valeur++;
    }
    
    // Bloc synchronisé
    public void incrementerBloc() {
        synchronized(this) {
            valeur++;
        }
    }
    
    public int getValeur() {
        return valeur;
    }
}

ExecutorService

import java.util.concurrent.*;

// Criação de um pool de threads
ExecutorService executor = Executors.newFixedThreadPool(5);

// Submeter tarefas
executor.submit(() -> {
    System.out.println("Tâche exécutée par " + Thread.currentThread().getName());
});

// Aguardar a conclusão de todas as tarefas
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);

Conclusão

Java é uma linguagem robusta e versátil que oferece uma ampla gama de recursos para desenvolver aplicações de qualidade. Ao dominar esses conceitos fundamentais, você poderá:

  • Criar aplicações completas e de alto desempenho
  • Compreender e utilizar o ecossistema Java (Spring, Hibernate etc.)
  • Desenvolver soluções corporativas confiáveis e de fácil manutenção
  • Implementar arquiteturas de software modernas

Para ir além, explore os frameworks Java populares, como o Spring Boot, a programação reativa com Project Reactor ou RxJava, e as APIs mais recentes, como os módulos (Java 9+) e os records (Java 16+).

InSkillCoach

Sobre InSkillCoach

Especialista em treinamento e tecnologias

Coach especializado em tecnologias avançadas e IA, apoiado pela GNeurone Inc.

Certificações:

  • AWS Certified Solutions Architect – Professional
  • Certificações Google Cloud
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
1.2k
143

Comentários

Os comentários são alimentados pelo GitHub Discussions

Conecte-se com o GitHub para participar da discussão

Link copiado!