Core Java: Complete Guide to Mastering the Fundamentals
A detailed guide to core Java concepts, from basic structures to object-oriented programming, with practical examples for all levels.
InSkillCoach
Core Java: Complete Guide to Mastering the Fundamentals
Java is one of the most widely used programming languages in the world, especially valued for its portability, robustness, and rich ecosystem. This guide introduces the fundamental concepts of Core Java, from the basics through to more advanced features.
Introduction to Java
Java was created by James Gosling at Sun Microsystems (now Oracle) and released in 1995. Its “Write Once, Run Anywhere” (WORA) philosophy revolutionized software development.
Main characteristics
- Object-oriented: Everything in Java is an object, except primitive types
- Platform-independent: Thanks to the JVM (Java Virtual Machine)
- Robust: Solid error handling, type checking at compile time
- Secure: Execution in a controlled environment (sandbox)
- Multi-threading: Built-in support for concurrent programming
- High performance: JIT (Just-In-Time) compiler optimizing execution
Installation and configuration
Installing the JDK (Java Development Kit)
# On Ubuntu/Debian
sudo apt update
sudo apt install openjdk-17-jdk
# On macOS with Homebrew
brew install openjdk@17
# On Windows
# Download from https://www.oracle.com/java/technologies/downloads/
Configuring environment variables
# On Linux/macOS
export JAVA_HOME=/path/to/jdk
export PATH=$PATH:$JAVA_HOME/bin
# On Windows
# Set JAVA_HOME and add %JAVA_HOME%\bin to PATH
First steps with Java
Basic structure of a Java program
// File: HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Compile and run
# Compile
javac HelloWorld.java
# Run
java HelloWorld
Data types and variables
Primitive types
// Integer numeric types
byte b = 127; // 8 bits, -128 to 127
short s = 32767; // 16 bits, -32,768 to 32,767
int i = 2147483647; // 32 bits, -2,147,483,648 to 2,147,483,647
long l = 9223372036854775807L; // 64 bits, very large range
// Floating-point numeric types
float f = 3.14f; // 32 bits
double d = 3.14159; // 64 bits
// Other primitive types
char c = 'A'; // 16 bits, Unicode character
boolean bool = true; // true or false
Variables and constants
// Variable declaration
int nombre;
nombre = 42;
// Declaration and initialization
String message = "Bonjour";
// Constants (final)
final double PI = 3.14159;
Operators
Arithmetic operators
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 (integer division)
int reste = a % b; // 1 (modulo)
// Increment and decrement
a++; // a = a + 1
b--; // b = b - 1
Comparison operators
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
Logical operators
boolean x = true, y = false;
boolean et = x && y; // false (logical AND)
boolean ou = x || y; // true (logical OR)
boolean non = !x; // false (logical NOT)
Control structures
Conditionals
// 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");
}
// Ternary expression
String statut = (age >= 18) ? "Majeur" : "Mineur";
Loops
// for loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// while loop
int compteur = 0;
while (compteur < 5) {
System.out.println(compteur);
compteur++;
}
// do-while loop
int j = 0;
do {
System.out.println(j);
j++;
} while (j < 5);
// for-each loop (for collections)
int[] nombres = {1, 2, 3, 4, 5};
for (int nombre : nombres) {
System.out.println(nombre);
}
Arrays and Collections
Arrays
// Declaring and initializing an array
int[] nombres = new int[5];
nombres[0] = 10;
nombres[1] = 20;
// Initialization with values
int[] valeurs = {10, 20, 30, 40, 50};
// Multidimensional array
int[][] matrice = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Iterating over an array
for (int i = 0; i < nombres.length; i++) {
System.out.println(nombres[i]);
}
Collections Framework
import java.util.*;
// List
List<String> liste = new ArrayList<>();
liste.add("Pomme");
liste.add("Banane");
liste.add("Orange");
System.out.println(liste.get(1)); // Banane
liste.remove("Pomme");
// Set (unique elements)
Set<Integer> ensemble = new HashSet<>();
ensemble.add(1);
ensemble.add(2);
ensemble.add(1); // Ignored because already present
System.out.println(ensemble.size()); // 2
// Map (key-value)
Map<String, Integer> map = new HashMap<>();
map.put("Pierre", 30);
map.put("Marie", 25);
System.out.println(map.get("Marie")); // 25
Object-Oriented Programming (OOP)
Classes and objects
// Class definition
public class Personne {
// Attributes (fields)
private String nom;
private int age;
// Constructor
public Personne(String nom, int age) {
this.nom = nom;
this.age = age;
}
// Methods
public void sePresenter() {
System.out.println("Je m'appelle " + nom + " et j'ai " + age + " ans.");
}
// Getters and 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;
}
}
// Using the class
Personne personne = new Personne("Alice", 30);
personne.sePresenter();
personne.setAge(31);
System.out.println(personne.getAge()); // 31
Inheritance
// Parent class
public class Animal {
protected String nom;
public Animal(String nom) {
this.nom = nom;
}
public void manger() {
System.out.println(nom + " mange.");
}
}
// Child class
public class Chien extends Animal {
private String race;
public Chien(String nom, String race) {
super(nom); // Call to parent constructor
this.race = race;
}
public void aboyer() {
System.out.println(nom + " aboie.");
}
// Method override
@Override
public void manger() {
System.out.println(nom + " le chien mange des croquettes.");
}
}
// Usage
Chien rex = new Chien("Rex", "Berger Allemand");
rex.manger(); // "Rex le chien mange des croquettes."
rex.aboyer(); // "Rex aboie."
Polymorphism
Animal animal1 = new Animal("Truc");
Animal animal2 = new Chien("Médor", "Labrador"); // Polymorphism
animal1.manger(); // "Truc mange."
animal2.manger(); // "Médor le chien mange des croquettes."
// animal2.aboyer(); // Compilation error, because animal2 is of type Animal
((Chien) animal2).aboyer(); // OK after cast
Interfaces
// Interface definition
public interface Nageur {
void nager();
}
// Interface implementation
public class Poisson extends Animal implements Nageur {
public Poisson(String nom) {
super(nom);
}
@Override
public void nager() {
System.out.println(nom + " nage rapidement.");
}
}
// Multiple implementation
public class Canard extends Animal implements Nageur {
public Canard(String nom) {
super(nom);
}
@Override
public void nager() {
System.out.println(nom + " nage lentement.");
}
}
// Usage
Nageur nageur1 = new Poisson("Nemo");
Nageur nageur2 = new Canard("Donald");
nageur1.nager(); // "Nemo nage rapidement."
nageur2.nager(); // "Donald nage lentement."
Abstract classes
// Abstract class
public abstract class Vehicule {
protected String marque;
public Vehicule(String marque) {
this.marque = marque;
}
// Concrete method
public void demarrer() {
System.out.println("Le véhicule démarre.");
}
// Abstract method (to be implemented by subclasses)
public abstract void accelerer();
}
// Implementing an abstract class
public class Voiture extends Vehicule {
public Voiture(String marque) {
super(marque);
}
@Override
public void accelerer() {
System.out.println("La voiture " + marque + " accélère.");
}
}
Exception handling
Try-catch-finally
try {
// Code that may throw an exception
int resultat = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
// Exception handling
System.out.println("Erreur: Division par zéro");
e.printStackTrace();
} finally {
// Code executed in all cases
System.out.println("Fin du traitement");
}
Custom exceptions
// Custom exception definition
public class AgeInvalideException extends Exception {
public AgeInvalideException(String message) {
super(message);
}
}
// Usage
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;
}
}
// Exception handling
Utilisateur utilisateur = new Utilisateur();
try {
utilisateur.setAge(200);
} catch (AgeInvalideException e) {
System.out.println("Erreur: " + e.getMessage());
}
Input/Output (I/O)
Reading files
import java.io.*;
// try-with-resources for automatic closing
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String ligne;
while ((ligne = reader.readLine()) != null) {
System.out.println(ligne);
}
} catch (IOException e) {
e.printStackTrace();
}
Writing files
try (BufferedWriter writer = new BufferedWriter(new FileWriter("sortie.txt"))) {
writer.write("Ligne 1");
writer.newLine();
writer.write("Ligne 2");
} catch (IOException e) {
e.printStackTrace();
}
I/O streams
// Console input
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Entrez votre nom: ");
String nom = scanner.nextLine();
System.out.println("Bonjour, " + nom + "!");
}
// Formatted output
System.out.printf("Température: %.1f°C%n", 22.5);
Generics
// Generic class
public class Boite<T> {
private T contenu;
public void mettre(T contenu) {
this.contenu = contenu;
}
public T prendre() {
return contenu;
}
}
// Usage
Boite<String> boiteTexte = new Boite<>();
boiteTexte.mettre("Hello");
String texte = boiteTexte.prendre();
Boite<Integer> boiteNombre = new Boite<>();
boiteNombre.mettre(42);
int nombre = boiteNombre.prendre();
Generic methods
public <T> void afficherTableau(T[] tableau) {
for (T element : tableau) {
System.out.println(element);
}
}
// Usage
String[] mots = {"Bonjour", "le", "monde"};
Integer[] nombres = {1, 2, 3, 4, 5};
afficherTableau(mots);
afficherTableau(nombres);
Lambda and Streams (Java 8+)
Lambda expressions
// Functional interface
interface Calculateur {
int calculer(int a, int b);
}
// Traditional approach
Calculateur addition = new Calculateur() {
@Override
public int calculer(int a, int b) {
return a + b;
}
};
// With lambda
Calculateur additionLambda = (a, b) -> a + b;
System.out.println(additionLambda.calculer(5, 3)); // 8
// Other examples
Runnable tache = () -> System.out.println("Tâche exécutée");
Comparator<String> comparateur = (s1, s2) -> s1.length() - s2.length();
Stream API
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
List<String> noms = Arrays.asList("Jean", "Marie", "Pierre", "Sophie");
// Filtering
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]
// Reduction
int somme = noms.stream()
.mapToInt(String::length)
.sum(); // 21
// Other operations
boolean tousLongs = noms.stream().allMatch(nom -> nom.length() > 3); // true
String concatenation = noms.stream().collect(Collectors.joining(", ")); // "Jean, Marie, Pierre, Sophie"
Multithreading and concurrency
Creating threads
// Method 1: Extend Thread
class MonThread extends Thread {
@Override
public void run() {
System.out.println("MonThread s'exécute");
}
}
// Method 2: Implement Runnable
class MaTache implements Runnable {
@Override
public void run() {
System.out.println("MaTache s'exécute");
}
}
// Usage
Thread thread1 = new MonThread();
thread1.start();
Thread thread2 = new Thread(new MaTache());
thread2.start();
// Lambda with Runnable
Thread thread3 = new Thread(() -> {
System.out.println("Tâche lambda s'exécute");
});
thread3.start();
Synchronization
public class Compteur {
private int valeur = 0;
// Synchronized method
public synchronized void incrementer() {
valeur++;
}
// Synchronized block
public void incrementerBloc() {
synchronized(this) {
valeur++;
}
}
public int getValeur() {
return valeur;
}
}
ExecutorService
import java.util.concurrent.*;
// Creating a thread pool
ExecutorService executor = Executors.newFixedThreadPool(5);
// Submit tasks
executor.submit(() -> {
System.out.println("Tâche exécutée par " + Thread.currentThread().getName());
});
// Wait for all tasks to finish
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
Conclusion
Java is a robust and versatile language that offers a wide range of features for building quality applications. By mastering these fundamental concepts, you will be able to:
- Build complete, high-performance applications
- Understand and use the Java ecosystem (Spring, Hibernate, etc.)
- Develop reliable, maintainable enterprise solutions
- Implement modern software architectures
To go further, explore popular Java frameworks such as Spring Boot, reactive programming with Project Reactor or RxJava, and more recent APIs such as modules (Java 9+) and records (Java 16+).
About InSkillCoach
Training and technology expert
Coach specializing in advanced technologies and AI, backed by GNeurone Inc.
Certifications:
- AWS Certified Solutions Architect – Professional
- Google Cloud certifications
- Microsoft Certified: DevOps Engineer Expert
- Certified Kubernetes Administrator (CKA)
- CompTIA Security+
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion