Back-end · formation gratuite
Java Training
Learn Java, one of the world's most popular programming languages
- Intermédiaire
- 13 chapitres
- Exemples de code
- 100 % gratuit
Introduction to Java
Java is an object-oriented, compiled, and cross-platform programming language created by James Gosling at Sun Microsystems (now Oracle) and released in 1995. Java is one of the most widely used languages in the world, particularly in enterprise application development, Android, and backend systems.
☕ What is Java?
Java is a compiled and object-oriented programming language. Java code is compiled into bytecode that runs on the Java Virtual Machine (JVM), allowing Java to be "write once, run anywhere" (WORA). Java is strongly typed and follows the object-oriented paradigm.
💡 Why is Java so popular?
- Cross-platform - "Write once, run anywhere" thanks to the JVM, works on Windows, Linux, macOS
- Widely used in enterprise - Language of choice for enterprise applications, backend systems, microservices
- Android development - Main language for developing Android applications
- Robust and secure - Automatic memory management, built-in security system, strong typing
- Vast ecosystem - Spring, Hibernate, Maven, Gradle, and thousands of libraries
- Massive community - Millions of developers, comprehensive documentation, active support
🚀 Why learn Java?
Java is an excellent choice for learning object-oriented programming and developing professional applications:
- ✅ Highly in demand - One of the most sought-after languages in the job market. Used by Google, Amazon, Netflix, LinkedIn, Uber
- ✅ Android development - Main language for creating Android mobile applications
- ✅ Enterprise applications - Industry standard for backend systems, microservices, banking applications
- ✅ Free and Open-Source - Open-source JDK, cross-platform, active community
- ✅ Rich ecosystem - Spring Framework, Hibernate, Maven, Gradle, and thousands of libraries
- ✅ Large community - Abundant support and resources, active forums, comprehensive documentation
- ✅ Stable career - Many job opportunities with good salaries
📋 Prerequisites for learning Java
To learn Java effectively, it is recommended to have:
- ✅ Basic computing - Know how to use a computer, create and edit files
- ✅ Programming logic - Understanding basic concepts (variables, conditions, loops) is recommended
- ✅ OOP concepts - Understanding classes, objects, inheritance is useful but you will learn them with Java
💡 Important note: To get started with Java, you need to install the JDK (Java Development Kit) from oracle.com or use OpenJDK. You can use an IDE like IntelliJ IDEA, Eclipse, or VS Code with the Java extension. To test quickly, you can use online environments like Repl.it or OnlineGDB.
🎯 Java Use Cases
Java is used in many fields:
- Android development - Main language for creating Android mobile applications
- Web applications - Spring Boot, Java EE to create web applications and REST APIs
- Enterprise applications - Backend systems, microservices, banking and financial applications
- Cloud Computing - Cloud application development with Spring Cloud, AWS SDK
- Game development - LibGDX, jMonkeyEngine to create video games
- Tools and frameworks - Maven, Gradle, Jenkins, Elasticsearch are written in Java
- Big Data - Hadoop, Spark use Java for processing large amounts of data
- Financial systems - Trading, banking systems, financial applications
📝 Basic Syntax
Java syntax is based on C/C++ but simplified. Java uses braces {} to define code blocks and is a strongly typed language, meaning you must declare the type of each variable.
// Premier programme Java
public class BonjourMonde {
public static void main(String[] args) {
System.out.println("Bonjour, monde !");
// Variables
String nom = "NiangProgrammeur";
int age = 25;
// Affichage formaté
System.out.println("Je m'appelle " + nom + " et j'ai " + age + " ans");
// Opérations simples
int resultat = 10 + 5;
System.out.println("10 + 5 = " + resultat);
}
}
💡 Important points about Java syntax:
- Java uses braces
{}to define code blocks (classes, methods, conditions, loops) - Comments use
//for a line, or/* */for multiple lines - Semicolon required
;at the end of each statement - Java is case-sensitive -
MyClassis different frommyclass - Each file must contain a public class with the same name as the file
- Main method - Entry point of any Java program:
public static void main(String[] args) - Naming conventions - Classes in PascalCase, methods/variables in camelCase, constants in UPPER_CASE
🔍 Detailed syntax example
Here is a complete example showing several aspects of Java syntax:
// Définition d'une classe
public class Calculatrice {
// Méthode pour calculer la moyenne
public static double calculerMoyenne(int[] nombres) {
if (nombres.length == 0) {
return 0;
}
int somme = 0;
for (int nombre : nombres) {
somme += nombre;
}
double moyenne = (double) somme / nombres.length;
return moyenne;
}
// Méthode principale
public static void main(String[] args) {
int[] notes = {15, 18, 12, 20, 16};
double moyenne = calculerMoyenne(notes);
System.out.println("La moyenne est : " + moyenne);
}
}
🔤 Variables
In Java, variables must be declared with a type before being used. Java is a statically typed language, meaning the type of a variable is determined at compile time and cannot change.
// Déclaration de variables
String nom = "Java"; // String (chaîne de caractères)
int age = 30; // int (entier)
double prix = 19.99; // double (nombre décimal)
boolean estActif = true; // boolean (booléen)
Object valeurNulle = null; // null (valeur nulle)
// Affichage
System.out.println(nom);
System.out.println(age);
System.out.println(prix);
System.out.println(estActif);
System.out.println(valeurNulle);
// Déclaration puis assignation
int nombre;
nombre = 10;
System.out.println(nombre);
// Variables finales (constantes)
final double PI = 3.14159; // Ne peut pas être modifiée
final String NOM_APPLICATION = "MonApp";
// Noms de variables valides
String nomUtilisateur = "Bassirou";
int ageUtilisateur = 25;
String _prive = "variable privée"; // Possible mais non recommandé
📌 Rules for variable names:
- Must start with a letter, underscore
_, or dollar$ - Can contain letters, numbers, underscores, and dollars
- Cannot contain spaces (use
camelCaseinstead) - Are case-sensitive (
age≠Age) - Cannot be Java keywords (
if,for,class, etc.) - Convention: use
camelCasefor variables (ex:userName) - For constants: use
UPPER_CASEwith underscores (ex:MAX_SIZE)
📊 Data Types
Java has two categories of data types: primitive types and object types (references). Here are the main ones:
// Types primitifs (8 types)
byte petitNombre = 127; // 8 bits (-128 à 127)
short nombreCourt = 32767; // 16 bits
int nombre = 42; // 32 bits (le plus utilisé)
long grandNombre = 1234567890L; // 64 bits (notez le L)
float decimal = 3.14f; // 32 bits (notez le f)
double decimalPrecis = 3.14159; // 64 bits (le plus utilisé)
char caractere = 'A'; // 16 bits (un seul caractère)
boolean estVrai = true; // true ou false
// Types objets (références)
String texte = "Hello"; // String (chaîne de caractères)
Integer nombreObjet = 42; // Wrapper pour int
Double decimalObjet = 3.14; // Wrapper pour double
// Collections
int[] tableau = {1, 2, 3, 4, 5}; // Tableau
ArrayList<Integer> liste = new ArrayList<>(); // Liste dynamique
HashMap<String, Integer> map = new HashMap<>(); // Map (clé-valeur)
// Vérifier le type
System.out.println(texte.getClass().getName()); // java.lang.String
System.out.println(((Object) nombre).getClass().getName()); // java.lang.Integer (auto-boxing)
// Conversion de types
String ageStr = String.valueOf(25); // Convertir en String
int ageInt = Integer.parseInt("25"); // Convertir en int
double prixDouble = Double.parseDouble("19.99"); // Convertir en double
📚 Java Data Types:
- Primitive types - byte, short, int, long, float, double, char, boolean
- String - Character strings (special class, immutable)
- Arrays - Fixed-size collections (int[], String[], etc.)
- Collections - ArrayList, HashMap, HashSet, etc. (from java.util package)
🔢 Operators
Java supports arithmetic, comparison, logical, assignment, and instance operators:
// Opérateurs arithmétiques
int a = 10;
int b = 3;
System.out.println(a + b); // Addition: 13
System.out.println(a - b); // Soustraction: 7
System.out.println(a * b); // Multiplication: 30
System.out.println(a / b); // Division entière: 3
System.out.println((double)a / b); // Division: 3.333...
System.out.println(a % b); // Modulo (reste): 1
System.out.println(Math.pow(a, b)); // Puissance: 1000.0
// Opérateurs de comparaison
System.out.println(a > b); // true (supérieur à)
System.out.println(a < b); // false (inférieur à)
System.out.println(a >= b); // true (supérieur ou égal)
System.out.println(a <= b); // false (inférieur ou égal)
System.out.println(a == b); // false (égalité)
System.out.println(a != b); // true (différent)
// Opérateurs logiques
boolean x = true;
boolean y = false;
System.out.println(x && y); // false (ET logique)
System.out.println(x || y); // true (OU logique)
System.out.println(!x); // false (NON logique)
// Opérateurs d'assignation
int c = 5;
c += 3; // Équivalent à c = c + 3 (c devient 8)
c -= 2; // Équivalent à c = c - 2 (c devient 6)
c *= 2; // Équivalent à c = c * 2 (c devient 12)
c /= 3; // Équivalent à c = c / 3 (c devient 4)
// Opérateur instanceof
String texte = "Java";
System.out.println(texte instanceof String); // true
🔀 Conditional Structures
Java uses if, else if and else for conditions. Code blocks are delimited by braces {}.
// Structure if simple
int age = 20;
if (age >= 18) {
System.out.println("Vous êtes majeur");
} else {
System.out.println("Vous êtes mineur");
}
// Structure if/else if/else
age = 15;
if (age >= 18) {
System.out.println("Vous êtes majeur");
System.out.println("Vous pouvez voter");
} else if (age >= 13) {
System.out.println("Vous êtes adolescent");
} else if (age >= 6) {
System.out.println("Vous êtes enfant");
} else {
System.out.println("Vous êtes un bébé");
}
// Conditions multiples
int note = 85;
String mention;
if (note >= 90) {
mention = "Excellent";
} else if (note >= 80) {
mention = "Très bien";
} else if (note >= 70) {
mention = "Bien";
} else if (note >= 60) {
mention = "Assez bien";
} else {
mention = "Insuffisant";
}
System.out.println("Votre mention : " + mention);
// Opérateur ternaire (expression conditionnelle)
age = 20;
String statut = (age >= 18) ? "Majeur" : "Mineur";
System.out.println(statut);
// Conditions avec &&/||
age = 25;
boolean permis = true;
if (age >= 18 && permis) {
System.out.println("Vous pouvez conduire");
} else {
System.out.println("Vous ne pouvez pas conduire");
}
// Switch-case
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("Autre jour");
}
🔄 Loops
Java offers several types of loops: for (classic and enhanced), while and do-while:
// Boucle for classique
for (int i = 0; i < 5; i++) {
System.out.println(i); // Affiche 0, 1, 2, 3, 4
}
// Boucle for avec début et fin
for (int i = 1; i <= 5; i++) {
System.out.println(i); // Affiche 1, 2, 3, 4, 5
}
// Boucle for avec pas
for (int i = 0; i < 10; i += 2) {
System.out.println(i); // Affiche 0, 2, 4, 6, 8
}
// Enhanced for loop (for-each) avec tableau
String[] fruits = {"pomme", "banane", "orange"};
for (String fruit : fruits) {
System.out.println("J'aime les " + fruit);
}
// Boucle for classique avec tableau
for (int i = 0; i < fruits.length; i++) {
System.out.println(i + ": " + fruits[i]);
}
// Boucle while
int compteur = 0;
while (compteur < 5) {
System.out.println(compteur);
compteur++;
}
// Boucle while avec break
compteur = 0;
while (true) {
System.out.println(compteur);
compteur++;
if (compteur >= 5) {
break; // Sortir de la boucle
}
}
// continue (passer à l'itération suivante)
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) { // Si i est pair
continue; // Passer au suivant
}
System.out.println(i); // Affiche seulement les impairs: 1, 3, 5, 7, 9
}
// Boucle do-while (exécute au moins une fois)
int x = 0;
do {
System.out.println(x);
x++;
} while (x < 5);
⚙️ Methods
Methods allow code reuse. In Java, we define a method with a return type, a name, and parameters. Methods can return values with return.
public class MethodesExemple {
// Méthode simple (sans paramètres)
public static void direBonjour() {
System.out.println("Bonjour !");
}
// Méthode avec paramètres
public static String saluer(String nom) {
return "Bonjour, " + nom + " !";
}
// Méthode avec plusieurs paramètres
public static int additionner(int a, int b) {
return a + b;
}
// Méthode avec surcharge (même nom, paramètres différents)
public static int additionner(int a, int b, int c) {
return a + b + c;
}
// Méthode avec type de retour void
public static void afficherInfo(String nom, int age) {
System.out.println(nom + " a " + age + " ans");
}
// Méthode principale
public static void main(String[] args) {
direBonjour(); // Appel de la méthode
String message = saluer("Java");
System.out.println(message); // "Bonjour, Java !"
int resultat = additionner(5, 3);
System.out.println(resultat); // 8
int resultat2 = additionner(1, 2, 3);
System.out.println(resultat2); // 6
afficherInfo("Bassirou", 25);
}
}
📋 Arrays
Arrays in Java are fixed-size data structures. They allow storing multiple elements of the same type.
// Création de tableaux
int[] nombres = {1, 2, 3, 4, 5};
String[] fruits = {"pomme", "banane", "orange"};
// Création avec taille
int[] tableau = new int[5]; // Tableau de 5 entiers (initialisés à 0)
// Accès aux éléments (index commence à 0)
System.out.println(fruits[0]); // "pomme" (premier élément)
System.out.println(fruits[fruits.length - 1]); // "orange" (dernier élément)
// Modification
fruits[1] = "mangue"; // Remplacer "banane" par "mangue"
// Longueur du tableau
System.out.println(fruits.length); // 3
// Parcourir un tableau avec for classique
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
// Parcourir avec enhanced for (for-each)
for (String fruit : fruits) {
System.out.println("J'aime les " + fruit);
}
// Tableaux multidimensionnels
int[][] matrice = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accès aux éléments
System.out.println(matrice[0][0]); // 1
System.out.println(matrice[1][2]); // 6
// Parcourir une matrice
for (int i = 0; i < matrice.length; i++) {
for (int j = 0; j < matrice[i].length; j++) {
System.out.print(matrice[i][j] + " ");
}
System.out.println();
}
🏗️ Object-Oriented Programming
Java is an object-oriented language. A class is a template for creating objects. Objects have attributes (data) and methods (functions).
// Définir une classe
class Personne {
// Attributs d'instance
private String nom;
private int age;
// Constructeur
public Personne(String nom, int age) {
this.nom = nom;
this.age = age;
}
// Méthode d'instance
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;
}
}
// Classe principale
public class ExemplePOO {
public static void main(String[] args) {
// Créer des objets (instances)
Personne personne1 = new Personne("Bassirou", 25);
Personne personne2 = new Personne("Aminata", 30);
// Utiliser les méthodes
personne1.sePresenter();
personne2.sePresenter();
// Accéder aux attributs via getters
System.out.println(personne1.getNom());
System.out.println(personne1.getAge());
}
}
📚 Collections
Java provides the Collections framework to manage groups of objects. The main collections are ArrayList, HashMap, HashSet, etc.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
// ArrayList (liste dynamique)
ArrayList<String> fruits = new ArrayList<>();
fruits.add("pomme");
fruits.add("banane");
fruits.add("orange");
fruits.add(1, "mangue"); // Insérer à l'index 1
System.out.println(fruits.get(0)); // "pomme"
System.out.println(fruits.size()); // 4
fruits.remove("banane");
fruits.remove(0);
// HashMap (dictionnaire clé-valeur)
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Bassirou", 25);
ages.put("Aminata", 30);
ages.put("Ibrahima", 28);
System.out.println(ages.get("Bassirou")); // 25
System.out.println(ages.containsKey("Aminata")); // true
// Parcourir un HashMap
for (String nom : ages.keySet()) {
System.out.println(nom + " a " + ages.get(nom) + " ans");
}
// HashSet (ensemble unique)
HashSet<String> villes = new HashSet<>();
villes.add("Dakar");
villes.add("Thiès");
villes.add("Dakar"); // Ignoré (déjà présent)
System.out.println(villes.size()); // 2
⚠️ Exception Handling
Java uses try-catch to handle errors. Exceptions allow errors to be handled elegantly without crashing the program.
// Try-catch simple
try {
int resultat = 10 / 0; // Division par zéro
} catch (ArithmeticException e) {
System.out.println("Erreur : Division par zéro !");
}
// Try-catch avec plusieurs catch
try {
int[] tableau = {1, 2, 3};
System.out.println(tableau[5]); // Index hors limites
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Erreur : Index invalide !");
} catch (Exception e) {
System.out.println("Erreur générale : " + e.getMessage());
}
// Try-catch-finally
try {
// Code qui peut générer une exception
int nombre = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Erreur : Format de nombre invalide !");
} finally {
System.out.println("Ce code s'exécute toujours");
}
// Lancer une exception
public static void verifierAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("L'âge ne peut pas être négatif");
}
System.out.println("Âge valide : " + age);
}
📁 File Handling
Java allows reading and writing files. We use FileReader, FileWriter, BufferedReader, etc.
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
// Écrire dans un fichier
try {
FileWriter writer = new FileWriter("fichier.txt");
writer.write("Bonjour Java !");
writer.close();
System.out.println("Fichier écrit avec succès");
} catch (IOException e) {
System.out.println("Erreur lors de l'écriture : " + e.getMessage());
}
// Lire un fichier
try {
FileReader reader = new FileReader("fichier.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String ligne;
while ((ligne = bufferedReader.readLine()) != null) {
System.out.println(ligne);
}
bufferedReader.close();
} catch (IOException e) {
System.out.println("Erreur lors de la lecture : " + e.getMessage());
}
// Utiliser try-with-resources (fermeture automatique)
try (FileWriter writer = new FileWriter("fichier.txt")) {
writer.write("Bonjour Java !\n");
writer.write("Ceci est la deuxième ligne\n");
System.out.println("Fichier écrit avec succès");
} catch (IOException e) {
System.out.println("Erreur : " + e.getMessage());
}
// Lire ligne par ligne avec try-with-resources
try (BufferedReader reader = new BufferedReader(new FileReader("fichier.txt"))) {
String ligne;
while ((ligne = reader.readLine()) != null) {
System.out.println(ligne);
}
} catch (IOException e) {
System.out.println("Erreur lors de la lecture : " + e.getMessage());
}
// Ajouter à un fichier (mode append)
try (FileWriter writer = new FileWriter("fichier.txt", true)) {
writer.write("Nouvelle ligne ajoutée\n");
System.out.println("Ligne ajoutée avec succès");
} catch (IOException e) {
System.out.println("Erreur : " + e.getMessage());
}
💡 Important note: In Java, it is recommended to use try-with-resources to ensure automatic file closure. This avoids resource leaks and simplifies code.
🎓 Next Steps
Congratulations! You now have a solid foundation in Java.
✅ What you learned:
- Java syntax and variables
- Data types (primitives and objects)
- Operators (arithmetic, comparison, logical)
- Conditional structures (if, else if, else, switch)
- Loops (for, while, do-while, enhanced for)
- Methods (definition, parameters, return, overloading)
- Arrays (declaration, manipulation, multidimensional)
- Object-Oriented Programming (classes, objects, constructors)
- Collections (ArrayList, HashMap, HashSet)
- Exception handling (try-catch-finally)
- File handling (FileReader, FileWriter, BufferedReader)
🚀 To go further:
- Inheritance and Polymorphism - Advanced OOP concepts
- Interfaces and Abstract classes - Abstraction in Java
- Packages and Modules - Code organization
- Spring Framework - Framework for enterprise applications
- Android development - Create mobile applications
- Microservices - Distributed architecture with Spring Cloud