Chapter 1: Introduction to programming in Oracle Java SE 21 LTS.

Advertisement

In-depth Oracle Java SE 21 LTS Course

This first chapter lays the foundation for working with Oracle Java SE 21 LTS, the LTS version supported by Oracle. Here you'll learn about the origins and history of the language, its philosophy, and Object-Oriented Programming (OOP), including detailed installation and configuration of the JDK on major operating systems. It also explains the complete development cycle: compilation, execution, debugging, and packaging (via JAR files) using the tools included in the JDK. It also describes the various applications and projects that can be developed with Java, and delves deeper into Object-Oriented Programming in Java. This guide lays the groundwork for addressing more advanced topics in later chapters.

Currently, I am studying Java SE So I've decided to create my first course on this programming language and thus learn, and help other students become Java programmers. It's a concise, no-nonsense, straight-to-the-point article to help you quickly learn how to develop software in Linux, a perfect guide to learn quickly and find work as soon as possible. The course is completely free with a Creative Commons license and the code is GPL. The course will be divided into chapters and I hope it will help you as much as it has me. The IDEs we'll be using are the Eclipse IDE, Visual Studio Code, and the Linux terminal. I've chosen the Java SE 21 JDK because it's an LTS version, but we're already on Java SE 24, which is a minor Oracle version.

1. Introduction to Java and Object-Oriented Programming (OOP)

Oracle Java SE 21 LTS is framed in the philosophy «Write Once, Run Anywhere», since the source code is compiled into bytecode, which is interpreted by the Java Virtual Machine (JVM). This allows the same application to run seamlessly on different operating systems without modification.

Object-Oriented Programming is the fundamental pillar of Java. Dividing code into classes and objects promotes modularity, maintainability, and reuse, which is essential in large and complex projects. Below, we delve into the basic principles of OOP.

1.1. Object-Oriented Programming in Java

OOP is based on four essential pillars:

  • Encapsulation: It consists of hiding the internal data of a class and exposing only the methods necessary for its manipulation. Access modifiers are used (private, protected, public) along with methods getter and setter. Example:

    java

          public class Persona {
              private String nombre; // Atributo privado
          
              public String getNombre() {
                  return nombre;
              }
          
              public void setNombre(String nombre) {
                  this.nombre = nombre;
              }
          }
  • Inheritance: It allows you to create new classes from existing classes, inheriting their attributes and methods to extend or specialize functionalities. Example:

    java

          public class Animal {
              public void comer() {
                  System.out.println("El animal está comiendo");
              }
          }
          
          public class Perro extends Animal {
              public void ladrar() {
                  System.out.println("El perro ladra");
              }
          }
          
          // Uso:
          Perro miPerro = new Perro();
          miPerro.comer();  // Método heredado
          miPerro.ladrar(); // Método propio
  • Polymorphism: It allows the same variable or method to behave differently depending on the object that contains it. For example, you can have a reference to a parent type and assign it to an object of a derived class, taking advantage of method overriding. Example:

    java

          Animal miAnimal = new Perro();
          miAnimal.comer(); // Se ejecuta el método definido en Animal
          // Para acceder a métodos específicos de Perro, se podría realizar un casting.
  • Abstraction: It consists of defining abstract classes or interfaces that establish a model or contract for the classes that implement them, leaving the concrete implementation to the derived classes. Example:

    java

          public abstract class Forma {
              public abstract double calcularArea();
          }
          
          public class Circulo extends Forma {
              private double radio;
              
              public Circulo(double radio) {
                  this.radio = radio;
              }
              
              @Override
              public double calcularArea() {
                  return Math.PI * radio * radio;
              }
          }

These principles facilitate the development of modular, scalable, and maintainable applications, cementing the importance of OOP in the Java ecosystem. I don't expect you to understand or know what object-oriented programming is; it's simply a first introduction, explaining it from scratch.

2. What is Oracle Java SE 21 LTS?

Oracle Java SE 21 LTS is the latest version of the Java language supported by Oracle. Its key features include:

  • Portability: Applications are compiled to bytecode, ensuring they run seamlessly on Windows, macOS, Linux, and other systems without modification.

  • Safety and Robustness: It features rigorous exception handling, an advanced Garbage Collector, and strict syntax that helps minimize runtime errors.

  • Extensive Standard Library: It offers an extensive set of APIs for managing common tasks, from data manipulation to accessing network services and databases.

These features make Oracle Java SE 21 LTS ideal for developing enterprise solutions, mobile and desktop applications, and even high-performance embedded systems.

3. History of the Java Language and its Inventor

Java was born at Sun Microsystems in the mid-1990s, thanks to the innovative vision of James Gosling and his team, who sought to create a simple, powerful, and portable language to meet the challenges of an ever-growing digital environment. Since its official launch in 1995, Java has transformed the software industry, providing robust and scalable solutions for developing cross-platform applications.

In 2010, Sun Microsystems was acquired by Oracle, which has since been the primary entity promoting and maintaining the language. Oracle has continued to evolve Java, implementing improvements in security, performance, and modernization of its APIs, solidifying Oracle Java SE 21 LTS as the preferred version for critical and large-scale projects.

4. Java Technologies

The Java ecosystem extends to diverse areas to adapt to multiple development needs:

  • Java Standard Edition (SE): The basis for developing desktop applications and utilities.

  • Java Enterprise Edition (EE): Oriented to distributed applications, web services and transactional systems.

  • Java Micro Edition (ME): Designed for mobile devices and embedded systems, taking advantage of limited resources.

  • JavaFX: Modern platform for creating sophisticated graphical interfaces, surpassing Swing in functionality and performance.

Each technology specializes in a specific area, allowing the full potential of language to be exploited.

5. What is the JDK?

The Oracle Java SE 21 LTS Java Development Kit (JDK) is the complete set of tools required to develop, compile, run, and debug Java applications. Its core components include:

  • The Compiler (javac): Converts source code (.java) to bytecode (.class) for execution on the JVM.

  • The JVM: It executes the bytecode on a hardware abstraction layer, ensuring portability.

  • The Standard Libraries: They provide an extensive set of APIs ready to use in any project.

  • Complementary Tools: Includes the debugger (jdb) for real-time analysis, utilities for generating documentation and the tool jar to package applications.

Mastering the JDK is essential to taking full advantage of Oracle Java SE 21 LTS.

6. Installing Oracle Java SE 21 LTS JDK on Different Operating Systems

Java environment variables are global settings set on the operating system that allow Java-related tools and programs (such as the compiler, the Java Virtual Machine, and other utilities) to correctly find and use the resources needed to compile and run applications.

The main environment variables in the context of Java and their functions are detailed below:

  1. JAVA_HOME

    • What is it? It is a variable that points to the root folder where the JDK (Java Development Kit) is installed.

    • What is it for? Allows programs and build tools (such as Maven, Gradle, Ant, and others) to quickly and easily locate all JDK resources, such as the compiler (javac), the Java Virtual Machine (java) and other utilities. This is essential for scripts and IDEs to know where to look for the Java development environment.

  2. PATH

    • What is it? It is a variable that contains a list of directories in which the operating system searches for program executables.

    • What is it for? By including the directory bin of the JDK (usually referenced through JAVA_HOME, For example, %JAVA_HOME%\bin on Windows or $JAVA_HOME/bin on Unix/Linux/macOS) in the environment variable PATH, you are allowed to run commands like java, javac, jar and others from any location in the terminal without having to specify the full path.

  3. CLASSPATH

    • What is it? It is a variable that tells the Java runtime environment where to locate the external classes and libraries needed to run a program.

    • What is it for? During compilation and execution, the JVM uses CLASSPATH to find the definitions of necessary classes and packages. If your project depends on external libraries (such as JAR files), you can include them in the CLASSPATH so they're accessible. While in many cases it's recommended to leave it at its default value (usually the current directory, indicated by a "."), in complex projects or when working without a dependency manager, it's useful to set it explicitly.

Summary:

  • JAVA_HOME is used to tell your system where the JDK is installed.

  • PATH It is set up so that you can access Java executables without providing full paths each time.

  • CLASSPATH helps the JVM locate classes and libraries needed to run your applications.

These variables are essential for properly configuring the Java development environment and ensure that all tools work seamlessly and seamlessly. Keeping them configured correctly is key both for working in the command line and for using IDEs and build systems that rely on these values.

To ensure an optimal development environment, it's essential to properly install the JDK and configure the appropriate environment variables. The process for Windows 11, macOS, and MX-Linux is detailed below.

Windows 11

6.1. In Windows 11

Step 1 – Download and Install the JDK:

  • Download the installer (file .exe) from for Oracle Java SE 21 LTS.

  • Run the installer and follow the wizard. By default, the JDK is installed in:

    C:\Program Files\Java\jdk-21

Step 2 – Setting Environment Variables:

  1. JAVA_HOME:

    • Right-click on “This PC” and select “Properties.”

    • Go to “Advanced system settings” and click “Environment variables…”.

    • Under “System Variables,” click “New…” and set:

      • Variable name: JAVA_HOME

      • Worth:

        C:\Program Files\Java\jdk-21
  2. PATH:

    • In the same window, select the variable Path and click “Edit…”.

    • Add a new entry:

      %JAVA_HOME%\bin
  3. CLASSPATH (Optional):

    • For a complete configuration, create a new variable:

      • Variable name: CLASSPATH

      • Worth:

        .;%JAVA_HOME%\lib

      (The “.” indicates the current directory; in Windows the separator is “;”).

Step 3 – Verification:

  • Open Command Prompt and run:

    bash

    java -version
    javac -version
  • The output should show Oracle Java version 21, confirming that the installation and configuration were successful.

MacOS

6.2. On MacOS

Since I don't have a MacOS computer, I can't verify that this solution is correct and works. I relied on Google to find the solution to install the JDK on the bitten apple operating systems. 

Step 1 – Download and Install the JDK:

  • Download the file .dmg either .pkg from the for Oracle Java SE 21 LTS.

  • Run the installer and follow the instructions. By default, the JDK is installed in:

    /Library/Java/JavaVirtualMachines/jdk-21.jdk/Contents/Home

Step 2 – Setting Environment Variables:

  1. JAVA_HOME:

    • Open your shell's configuration file (for example, ~/.zshrc either ~/.bash_profile) and adds:

      bash

      export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-21.jdk/Contents/Home
  2. PATH:

    • In the same file, add:

      bash

      export PATH=$JAVA_HOME/bin:$PATH
  3. CLASSPATH (Optional):

    • Also add:

      bash

      export CLASSPATH=.:$JAVA_HOME/lib

      (On macOS, “:” is the path separator and “.” indicates the current directory.)

Step 3 – Apply Settings and Verify:

  • Save the changes and reload the configuration file:

    bash

    source ~/.zshrc

    (EITHER source ~/.bash_profile as appropriate)

  • Open Terminal and run:

    bash

    java -version 
    javac -version
  • The output should confirm the installation of Oracle Java SE 21 LTS.

6.3. On Debian, Ubuntu, Linux Mint and MX‑Linux

 

Step 1 – Installing the JDK:

You have two options:

Option A – Installation via Package Manager:

  • If Oracle Java SE 21 LTS or an equivalent version (such as OpenJDK 21) is available in the repositories, run:

    bash

    $ sudo apt install openjdk-21-jdk

Option B – Manual Installation:

  • Download the file from Oracle, Java SE 21 LTS.

  • Extract the contents into a directory, for example:

    /opt/java/jdk-21

Step 2 – Setting Environment Variables:

  • Open your shell configuration file (for example, ~/.bashrc either ~/.profile) and adds:

    1. JAVA_HOME:

      bash

      Advertisement
      export JAVA_HOME=/opt/java/jdk-21
    2. PATH:

      bash

      export PATH=$JAVA_HOME/bin:$PATH
    3. CLASSPATH (Optional):

      bash

      export CLASSPATH=.:$JAVA_HOME/lib

      (In Linux, “:” is the separator and “.” indicates the current directory.)

Step 3 – Apply Settings and Verify:

  • Save the changes and reload the file:

    bash

    source ~/.bashrc

    (EITHER source ~/.profile)

  • In the terminal, verify the installation:

    bash

    $ java -version 
    $ javac -version
  • The output should show Oracle Java SE 21 LTS, confirming the correct installation and configuration.

7. Compiling, Running, Debugging, and Packaging with JAR

7.1. Compiling and Running from the Command Line

Consider the classic “Hello World” example:

java

public class HolaMundo {
    public static void main(String[] args) {
        System.out.println("Hola Mundo");
    }
}
  1. Compilation:

    bash

    javac HolaMundo.java

    This will generate the file HolaMundo.class.

  2. Execution:

    bash

    java HolaMundo

7.2. Debugging with the JDB Debugger

Oracle Java SE 21 LTS includes the debugger jdb, which allows you to inspect the execution flow and variable values. For example, to calculate the factorial of a number:

java

public class DepuracionEjemplo {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            int factorial = calcularFactorial(i);
            System.out.println("El factorial de " + i + " es: " + factorial);
        }
    }

    public static int calcularFactorial(int num) {
        int resultado = 1;
        for (int i = 1; i <= num; i++) {
            resultado = resultado * i; // Punto de interrupción recomendado.
        }
        return resultado;
    }
}

Steps to use jdb:

  1. Compile the program:

    bash

    javac DepuracionEjemplo.java
  2. Start the debugger:

    bash

    jdb DepuracionEjemplo
  3. Set a breakpoint (e.g. on the calculation line):

    bash

    stop at DepuracionEjemplo:15

    (Adjust the line number if necessary.)

  4. Run the program in debug mode:

    bash

    run
  5. Inspect variables:

    bash

    print i 
    print resultado
  6. Use step to advance line by line and cont to continue to the next breakpoint or finish.

7.3. Packaging and Using JAR Files

Packaging an entire application into a JAR file is essential for its distribution. A JAR is a compressed file that includes the bytecode and all necessary resources, along with a manifest that defines the entry point.

Steps to create a JAR file:

  1. Create a manifest file: Create a file called manifest.txt with the following content:

    Main-Class: HolaMundo

    (Leave a blank line at the end.)

  2. Package the JAR: Run:

    bash

    jar cfm HolaMundo.jar manifest.txt HolaMundo.class
    • c creates the JAR file.

    • f defines the file name.

    • m use the custom manifest.

  3. Check Content: List the contents with:

    bash

    jar tf HolaMundo.jar
  4. Run the JAR: Launch the app with:

    bash

    java -jar HolaMundo.jar

    The JVM will use the manifest to locate the method main.

8. Open Source Java Programming IDEs

Integrated Development Environments (IDEs) streamline development with features such as autocompletion, refactoring, and visual debugging. For Oracle Java SE 21 LTS, the following are recommended:

  • Eclipse: With a broad plugin ecosystem and an active community that makes managing complex projects easy.

  • NetBeans: With native integration with the Oracle JDK, it simplifies development and debugging.

  • IntelliJ IDEA Community Edition: Noted for its smart autocompletion and powerful refactoring tools.

  • Visual Studio Code (VS Code): A lightweight editor that, through specialized extensions (for example, the Java Extension Pack), allows you to manage projects, debug, and manage dependencies in an agile and modern way.

9. Managing Libraries and Dependencies with Maven

Maven is the standard tool for managing Java projects. Its advantages include:

  • Centralization in pom.xml: All dependencies, plugins and configurations are defined in a single file.

  • Automation: Maven downloads, updates, and organizes the necessary libraries, which greatly simplifies maintenance.

  • Standardized Structure: Facilitates continuous integration and automated deployment following widely recognized conventions.

Basic example of pom.xml:

xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ejemplo</groupId>
    <artifactId>hola-mundo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- Dependencias definidas aquí -->
    </dependencies>
</project>

10. Features of Oracle Java SE 21 LTS

Oracle Java SE 21 LTS features:

  • Total Portability: Bytecode generation allows the same application to run on multiple systems without modification.

  • Safety and Robustness: Advanced exception handling and an efficient Garbage Collector provide a reliable environment.

  • Object Orientation: It facilitates code modularity, reuse, and scalability, ideal for large-scale projects.

  • Concurrency Support: It incorporates native tools for multithreading and parallelization programming, promoting high-performance applications.

  • Broad Ecosystem: Compatible with extensive standard libraries, tools like Maven, and various IDEs, meeting the needs of the modern developer.

11. What's New in Oracle Java SE 21 LTS

This LTS release introduces improvements aimed at current development challenges:

  • Performance Optimization: Improvements to JVM startup and application execution in both on-premises and cloud environments.

  • Language Refinements: Lambda expressions, switch expressions and pattern matching more powerful and concise, making it easier to write clear and efficient code.

  • API Modernization: New features in collections, data processing, and network operations, integrating modern paradigms.

  • Innovations in Concurrency: The addition of Virtual Threads and improvements in parallelization enable the development of scalable, high-performance applications.

  • Enhanced Security: New authentication and encryption mechanisms strengthen protection against vulnerabilities.

12. Applications and Projects that Can be Developed in Java

Oracle Java SE 21 LTS is a versatile language that allows you to tackle a wide range of projects, such as:

  • Business Applications: Management systems, CRMs and ERPs using frameworks such as Spring or Jakarta EE.

  • Web Applications: Development of RESTful websites and services using frameworks such as Spring Boot and JavaServer Faces (JSF).

  • Desktop Applications: Complex tools and interfaces developed with JavaFX or Swing.

  • Mobile Applications: Although Android uses a modified version of Java, its ecosystem remains fundamental.

  • Microservices and Cloud Computing: Implementation of microservices-based architectures, ideal for cloud deployment.

  • Integrated Applications and IoT: Development of solutions for embedded devices or resource-limited environments.

  • Games and Multimedia Applications: From simple desktop games to advanced multimedia applications.

  • Big Data and Data Analysis: Java-based frameworks such as Apache Hadoop and Apache Spark facilitate the processing and analysis of large volumes of data.

These possibilities demonstrate Java's versatility and its ability to respond to the needs of different sectors.

13. Explanatory Program "Hello World" in Java

The following is the classic "Hello World" program, which illustrates the basic structure of an application in Oracle Java SE 21 LTS:

java

public class HolaMundo {
    public static void main(String[] args) {
        System.out.println("Hola Mundo");
    }
}

Code Breakdown:

  • Class Definition: The public class is declared HolaMundo.

  • Main Method (main): It is the entry point of the program, defined as public static void main(String[] args).

  • Output to Console: The instruction System.out.println("Hola Mundo"); prints the message to the terminal.

To compile and run:

  1. Compilation:

    bash

    javac HolaMundo.java
  2. Execution:

    bash

    java HolaMundo

14. Conclusions

This chapter has laid the fundamental foundation for mastering Oracle Java SE 21 LTS. It has presented the language's philosophy and the principles of Object-Oriented Programming (OOP). It has detailed practical cases ranging from installing and configuring the JDK on different operating systems to the complete application development cycle (compilation, execution, debugging, and packaging into JAR files). It has also demonstrated Java's great versatility, allowing for the development of projects in diverse areas, from enterprise systems to Big Data and IoT applications.

The JAR packaging example and using the debugger jdb They highlight the importance of understanding the internal flow of the program to efficiently detect and correct errors.

15. Chapter Summary

  • Philosophy and Foundations: Principles of robustness, security, and portability that underpin Oracle Java SE 21 LTS.

  • Installing and Configuring the JDK: Detailed guide for Windows 11, macOS, and MX‑Linux, with complete configuration of environment variables (JAVA_HOME, PATH, and optional CLASSPATH).

  • Application Life Cycle: Process that covers from compilation and execution to debugging (jdb) and packaged into JAR files.

  • What's New and Features: Performance improvements, language refinements, API modernization, concurrency innovations, and enhanced security.

  • Applications and Projects: Broad possibilities ranging from business and web applications to IoT, gaming, and Big Data.

  • Practical Example: The “Hello World” program exemplifies the basic development flow with Oracle Java SE 21 LTS.

16. References

  1. Oracle Java Official Site: Official Oracle Java SE downloads and information:

  2. OpenJDK: OpenJDK Project Documentation and Resources:

  3. Apache Maven: Tutorials and documentation for Java project management:

17. Looking Ahead

With the foundations you've learned in this chapter, you'll be ready to delve into more complex topics such as modular programming, continuous integration, automated deployment, and creating microservices in distributed environments. The experience you gain in configuring and managing JAR files, and mastering debugging and optimization techniques, will prepare you to tackle larger and more complex projects.

If at any point a relevant section is identified as missing from this chapter, it will be dynamically integrated into future revisions to keep this guide complete and up-to-date.

This revised and expanded document offers a comprehensive and detailed overview of the essential foundations of Oracle Java SE 21 LTS. This reference provides all the sections you need to begin your journey into the fascinating world of Java, and leaves room for future additions or expansions based on learning needs and technological developments.

Welcome to the world of Oracle Java SE 21 LTS and a journey full of development, innovation, and discovery!

 

Our score
Click to rate this post!
(Votes: 0 Average: 0)
Advertisement
Share on social media...

Deja un comentario

Your email address will not be published. Required fields are marked *

Basic information on data protection
ResponsibleJavier Cachón Garrido +info...
PurposeManage and moderate your comments. +info...
LegitimationConsent of the concerned party. +info...
RecipientsAutomattic Inc., USA to spam filtering. +info...
RightsAccess, rectify and cancel data, as well as some other rights. +info...
Additional informationYou can read additional and detailed information on data protection on our page política de privacidad.

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.

Scroll al inicio

Descubre más desde javiercachon.com

Suscríbete ahora para seguir leyendo y obtener acceso al archivo completo.

Seguir leyendo