Sign In
Sign In

Installing Java on Ubuntu 22.04

Installing Java on Ubuntu 22.04
Hostman Team
Technical writer
Java
04.03.2024
Reading time: 7 min

The Java language is used in web development, writing desktop software, creating computer and mobile games (Android), as well as in scientific research and the financial sector. Java's popularity and prevalence are due to its security, application scalability, and adaptability.

This article will describe in detail the process of installing Java on Ubuntu. You will need a server with the Ubuntu 22.04 operating system, which you can order at Hostman. 

Installing Java

Before we proceed directly to the installation, we should talk about the existing versions of Java and its main components: JDK and JRE.

JRE is a software environment in which Java programs run. It includes JVM and Java class libraries.

JDK is a development platform for creating Java applications. It includes the JRE, compiler, debugger, and other useful developer tools.

At the time of writing, the latest version of Java is Java SE 21. It will be supported until September 2026. 

Let's look at the two most popular Java builds: OpenJDK and Oracle JDK. The former is an open-source version, and the latter is proprietary, for the use of which, in commercial developments, you need to pay. There is no difference between them for the average user. When installing OpenJDK, you can only install the JRE; in the case of Oracle JDK, both the JDK and the JRE will be installed.

In this article, we will describe installing both versions. After installation, we will tell you how to configure the use of a specific version by default and how to remove unnecessary ones from those installed on the OS.

Installing OpenJDK on Ubuntu

Here, we will be installing Java 19 on Ubuntu. 

First, let's update the list of apt packages in our system:

sudo apt update

Now, let's check whether Java is already installed in our system:  

java -version

In the output, you will see a message similar to the one below. The list of the available versions may vary.

Image4

To install Java on Ubuntu, use the command suggested by the console:

sudo apt install version_name

In our case, to download JRE from OpenJDK 19 to the server, we will enter openjdk-19-jre-headless instead of version_name, like this:

sudo apt install openjdk-19-jre-headless

Image9

After the installation is complete, check the Java version again: 

java -version

If the system displays your Java version, you have successfully installed Java on Ubuntu.

Image5

In addition to the JRE, you can also install the JDK.

To do this, use the command mentioned above:

sudo apt install version_name

However, this time, instead of version_name, enter openjdk-19-jdk-headless:

sudo apt install openjdk-19-jdk-headless

Image19

Now check that the JDK was installed successfully

javac -version

The system should respond with the following line:

Image1

This completes the installation of Java 19 on Ubuntu. If you want to install a different version, for example 17, simply replace the number 19 in the commands with 17.

Cloud Servers for your needs from $4/mo

Installing Oracle JDK on Ubuntu

We will install Java 17 on Ubuntu. First, we need to go to the Oracle website and find the "Compressed Archive" for our CPU type (ARM64 or x64). 

To check the CPU type of your Ubuntu server, run the command:

dpkg --print-architecture

Image10

In our case, it shows amd64, which means we should use the x64 archive.

Copy the download link to the clipboard.

Image14

Now you can download directly to the server using the wget command:

wget your_link

So, in our case:

wget https://download.oracle.com/java/17/archive/jdk-17.0.10_linux-x64_bin.tar.gz

Image3

Next, check the checksum of the downloaded archive: 

sha256sum jdk-17.0.10_linux-x64_bin.tar.gz

Image13

And compare it to the checksum on the website. To do this, click on sha256 next to the archive.

Here's the checksum we get on the website:

Image8

As you can see, the checksums match.

Now, unpack the archive into a folder on the server.

First, let's create a directory into which we will unpack the archive:

sudo mkdir -p path_to_directory

For example:

sudo mkdir -p /usr/lib/jvm

Next, unpack all the files of the downloaded archive into it.

sudo tar -zxvf jdk-17.0.10_linux-x64_bin.tar.gz -C /usr/lib/jvm

Now you can proceed to the installation. 

We will perform it using PPA. To add the PPA repository we will use the command below:

sudo add-apt-repository ppa:linuxuprising/java

Image18

After this, update the list of apt packages:

sudo apt update

And then install Oracle JDK 17 on the server:

sudo apt install oracle-java17-installer --install-recommends

When a message appears on the screen, as in the picture below, scroll down and click Ok.

Image12

Next, select Yes.

Image17

Upon completion, we will check if everything went well. To do this, enter the command we are already familiar with:

java -version

In response, you should receive a similar message:

Image11

As you can see, Oracle JDK 17 has been successfully installed to the server.

Let's also check the compiler installation:

javac -version

Image2

Installation of Java 17 on Ubuntu is complete.

Using one version to work with Java

In this article we install two versions of Java on a server. In practice, there may be more than two. In such cases, you can select a particular version as the default one. To do this, enter the following command into the terminal:

sudo update-alternatives --config java

As a result, the system will display all the versions on the server, as shown in the screenshot below.

Image7

To select your default version, enter its serial number in the line shown in the left column. To leave it as it is, press Enter.

This procedure can also be performed for compiler versions by replacing java with javac at the end of the command:

sudo update-alternatives --config javac

Image6

Removing Java

If, at some point, you no longer need one of the versions, you can safely delete it. Let's say you have installed the OpenJDK Java 16 on Ubuntu 22.04. To remove it, enter the following command into the terminal:

sudo apt purge openjdk-16*

If you want to remove every OpenJDK version installed on the server, use the command above without specifying the version.

In the case of Oracle Java, replace openjdk* in the command above with oracle-java*.

If you have installed Java 16 on Ubuntu, enter the following command into the console:

sudo apt purge oracle-java16-installer

If you need to remove another Java version, just change the version number in the command.

The JAVA_HOME variable

JAVA_HOME is used in many programs developed in Java. It points to the directory the JDK is installed to. 

To find out this directory, open the list of versions, as described in the section above:

sudo update-alternatives --config java

Image7

Now we know the location of Oracle Java 17 and OpenJDK 19. Since our example uses Oracle Java 17 by default, we copy the address specifically for it.

Now, use the copied address in the following command:

echo export JAVA_HOME="/usr/lib/jvm/java-17-oracle" >> ~/.bashrc

And then run:

source ~/.bashrc

Now let's check the changes made:

echo $JAVA_HOME

If the terminal displays the line shown below, everything was successful:

Image16

Managed solution for Backend development

Testing Java

Let's check that everything is installed and working correctly. To do this, we will create a simple program displaying a greeting on the screen.

1. Create a program file:

sudo nano example.java

2. Then write the code for our program:

public class example { 
    public static void main(String[] args) {
        System.out.println("Hello, User! Java is working successfully.");
    }
}

Save the file and close the editor.

3. Now compile the program:

javac example.java

4. And launch it:

java example

The console should output the phrase that was placed in the System.out.println method. If it does, then everything works correctly.

Conclusion

In the article, we examined how to install Java on Ubuntu 22.04. We have  shown how to install different versions of Java on the Ubuntu server and remove them. 

Java
04.03.2024
Reading time: 7 min

Similar

Java

Java Date Format

Handling dates and times effectively is a critical aspect of many software applications. In Java, the SimpleDateFormat class from the java.text package offers developers a robust mechanism for formatting Date objects into strings and parsing strings back into Date objects. This guide explores the features, use cases, and best practices for leveraging SimpleDateFormat in your Java projects. Overview of SimpleDateFormat A method for creating unique patterns for date and time data representation is offered by SimpleDateFormat. These patterns are versatile, allowing developers to adapt date formats to their specific application requirements. Here’s an introductory example: import java.text.SimpleDateFormat; import java.util.Date; public class SimpleDateFormatDemo { public static void main(String[] args) { SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); Date currentDate = new Date(); System.out.println("Formatted Date: " + formatter.format(currentDate)); } } This sample produces a string that is formatted in accordance with the given pattern and contains the current date and time: Formatted Date: 07/01/2025 14:35:00 Pattern Syntax for Formatting Dates The SimpleDateFormat class employs a symbolic pattern language to precise how dates and times should appear. Below is a table summarizing some key symbols: Symbol Description Example y Year 2025 (yyyy), 25 (yy) M Month 01 (MM), Jan (MMM) d Day of the month 07 (dd) H Hour (0-23) 14 (HH) h Hour (1-12) 02 (hh) m Minute 35 (mm) s Second 00 (ss) a AM/PM marker PM E Day of the week Tue (EEE), Tuesday (EEEE) z Time zone PST (z), Pacific Standard Time (zzzz) d Day of the month 07 (dd) H Hour (0-23) 14 (HH) h Hour (1-12) 02 (hh) m Minute 35 (mm) s Second 00 (ss) a AM/PM marker PM E Day of the week Tue (EEE), Tuesday (EEEE) z Time zone PST (z), Pacific Standard Time (zzzz) Combining these symbols allows developers to create highly tailored date and time formats. Customizing Date Formats Using SimpleDateFormat, you can craft custom formats to suit various requirements. Here’s an example demonstrating three distinct patterns: import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatExamples { public static void main(String[] args) { Date currentDate = new Date(); SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat verboseFormat = new SimpleDateFormat("EEEE, MMMM dd, yyyy"); SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a z"); System.out.println("ISO Format: " + isoFormat.format(currentDate)); System.out.println("Verbose Format: " + verboseFormat.format(currentDate)); System.out.println("Time Format: " + timeFormat.format(currentDate)); } } Sample Output: ISO Format: 2025-01-07 Verbose Format: Tuesday, January 07, 2025 Time Format: 02:35 PM PST Parsing Strings to Date Objects SimpleDateFormat also facilitates converting string representations of dates back into Date objects. This is especially useful for handling user input or reading data from external sources. import java.text.SimpleDateFormat; import java.util.Date; public class DateParsingDemo { public static void main(String[] args) { String inputDate = "07-01-2025 14:35:00"; SimpleDateFormat parser = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); try { Date parsedDate = parser.parse(inputDate); System.out.println("Parsed Date: " + parsedDate); } catch (Exception e) { System.out.println("Parsing failed: " + e.getMessage()); } } } Expected Output: Parsed Date: Tue Jan 07 14:35:00 PST 2025 Incorporating Time Zones The setTimeZone method in SimpleDateFormat allows for explicit handling of different time zones. Here’s an example: import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class TimeZoneHandling { public static void main(String[] args) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println("UTC Time: " + formatter.format(new Date())); formatter.setTimeZone(TimeZone.getTimeZone("America/New_York")); System.out.println("New York Time: " + formatter.format(new Date())); } } Output Example: UTC Time: 2025-01-07 22:35:00 UTC New York Time: 2025-01-07 17:35:00 EST Locale-Aware Formatting The SimpleDateFormat class supports locale-specific date formatting. By specifying a Locale, you can adapt your application for different regions and languages: import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class LocaleFormatting { public static void main(String[] args) { Date today = new Date(); SimpleDateFormat usFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy", Locale.US); SimpleDateFormat frFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy", Locale.FRANCE); System.out.println("US Format: " + usFormatter.format(today)); System.out.println("French Format: " + frFormatter.format(today)); } } Output Example: US Format: Tuesday, January 07, 2025French Format: mardi, janvier 07, 2025 Working with Legacy Code For projects that rely on legacy systems, SimpleDateFormat can be instrumental in ensuring compatibility with older data formats. By crafting patterns that match the specific requirements of legacy systems, developers can seamlessly bridge modern and older systems. However, it is critical to perform rigorous testing when working with legacy code. Edge cases like leap years, daylight saving time adjustments, or unusual formats often surface in older implementations. Developers should document the specific formats being used and verify the results using multiple test cases. In certain situations, refactoring legacy systems to use modern libraries like DateTimeFormatter may offer long-term benefits. While it might require upfront effort, the enhanced performance and reduced bug risk in newer libraries often justify the transition. Date Validation Techniques Validating dates is a common requirement in applications that accept user input. With SimpleDateFormat, you can ensure that input strings conform to the expected format before further processing. For example: import java.text.SimpleDateFormat; import java.util.Date; public class DateValidation { public static void main(String[] args) { String dateString = "31-02-2025"; SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); formatter.setLenient(false); try { Date validatedDate = formatter.parse(dateString); System.out.println("Valid Date: " + validatedDate); } catch (Exception e) { System.out.println("Invalid Date: " + e.getMessage()); } } } Output Example: Invalid Date: Unparseable date: "31-02-2025" Using the setLenient(false) method ensures that only logically valid dates are accepted, reducing the risk of errors in downstream processes. Common Pitfalls and Recommendations Thread Safety: Avoid sharing SimpleDateFormat instances across multiple threads. Use ThreadLocal or Java’s DateTimeFormatter for thread-safe alternatives. Error Handling: Always handle potential ParseException errors when parsing strings. ISO Standards: Utilize ISO 8601 formats (e.g., yyyy-MM-dd'T'HH:mm:ss'Z') for better interoperability. Dynamic Time Zones: Refrain from hardcoding time zones; instead, fetch them dynamically when necessary. Input Validation: Before parsing, make sure the input strings have the correct format. Transitioning to Modern Alternatives With the introduction of the java.time package in Java 8, many developers prefer DateTimeFormatter over SimpleDateFormat for its enhanced features and thread safety. import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class ModernDateFormatting { public static void main(String[] args) { LocalDateTime currentDateTime = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println("Formatted Date-Time: " + currentDateTime.format(formatter)); } } Sample Output: Formatted Date-Time: 2025-01-07 14:35:00 Additionally, DateTimeFormatter supports advanced features such as optional sections, localized styles, and predefined constants for ISO-compliant formats. These features make it a more versatile and robust choice for modern applications. Final Thoughts SimpleDateFormat remains a practical choice for date and time handling in Java. However, it is essential to understand its limitations, especially in terms of thread safety and modern compatibility. By adopting best practices and considering newer options like DateTimeFormatter, you can ensure robust and efficient date manipulation in your Java applications. Whether you are working with legacy systems, processing user inputs, or developing new features, a thorough knowledge of Java's date formatting features will empower you to handle date and time operations with confidence and precision. In addition, check out our app platform to find cloud apps, such as React, Angular, Vue and more.
15 January 2025 · 8 min to read
Java

Java main() Method

The main method in Java is a fundamental component for any standalone application. It serves as the entry point where the program begins execution. Understanding the syntax and functionality of this method is crucial for every Java programmer. This article delves into the specifics of the main method, explaining its syntax, the role of command-line arguments, and providing practical examples to illustrate its use. Syntax Explanation: public static void main(String[] args) The Java main method is defined as: public static void main(String[] args) Breaking down the syntax: public: This is an access modifier, meaning the method is accessible from anywhere. static: This keyword means the method belongs to the class rather than an instance of the class. It can be invoked without creating an object of the class. void: This signifies that the method does not return any value. main: This is the name of the method. The Java runtime environment looks for this specific method signature to start execution. String[] args: This parameter is an array of String objects, which stores command-line arguments passed to the program. Understanding the String[] args Parameter The String[] args parameter in the main method is crucial for passing information to the program at runtime. Each element in this array is a command-line argument provided when the program is executed. For example, if a program is run with java MyClass arg1 arg2, args[0] would be arg1 and args[1] would be arg2. public class MyClass { public static void main(String[] args) { for (String arg : args) { System.out.println(arg); } } In the above code, each command-line argument passed to the program is printed to the console. How to Use Command-Line Arguments Command-line arguments allow users to pass data into a Java program at the time of execution, making the program more flexible and dynamic. Here's a simple example of how to use command-line arguments in a Java program: public class SumArgs { public static void main(String[] args) { int sum = 0; for (String arg : args) { sum += Integer.parseInt(arg); } System.out.println("Sum: " + sum); } } If this program is run with java SumArgs 10 20 30, it will output Sum: 60. This demonstrates how command-line arguments can be used to input data without modifying the program's source code. Typical Use Cases and Examples Configuration Parameters: Command-line arguments are often used to pass configuration settings to a program. For example, specifying the path to a configuration file or setting a debug mode. public class ConfigLoader { public static void main(String[] args) { if (args.length > 0) { String configFilePath = args[0]; System.out.println("Loading configuration from: " + configFilePath); // Load and process the configuration file } else { System.out.println("No configuration file path provided."); } } } File Processing: Programs that perform operations on files often accept file paths as command-line arguments. public class FilePrinter { public static void main(String[] args) { if (args.length > 0) { String filePath = args[0]; // Code to read and print file content } else { System.out.println("Please provide a file path."); } } } Testing and Debugging: Command-line arguments can be used to quickly test and debug different scenarios by changing the input parameters without altering the source code. Conclusion The public static void main(String[] args) method is an essential part of any Java application. Its syntax and functionality are designed to provide a standardized entry point for program execution. Understanding how to leverage String[] args for command-line arguments can significantly enhance the flexibility and utility of your programs. By mastering the main method, Java developers can build more dynamic and configurable applications, making their code more versatile and easier to manage.
31 July 2024 · 4 min to read
Java

Installing Java Using apt on Ubuntu

Java and the JVM (Java Virtual Machine) are often used in various applications. Therefore, it's important to know how to install free packages and alternative releases from Oracle, including JRE (Java Runtime Environment) and JDK (Java Development Kit).  This tutorial will guide you through installing Java on Ubuntu using apt and selecting the preferred version. Prerequisites You will need a system (your local machine or a cloud server) with Ubuntu 20.04 pre-installed, with root and sudo accounts, and a configured firewall. Installing JRE/JDK The simplest way to get started is to use the release included in the standard Ubuntu package. Ubuntu 22.04 comes with OpenJDK 11, which includes open-source JRE and JDK packages. First, download updates to the package index: sudo apt update Before installing Java on Ubuntu, check if it has already been installed: java -version If Java is not installed, you will see: Command 'java' not found, but can be installed with:apt install openjdk-11-jre-headless  # version 11.0.20.1+1-0ubuntu1~22.04, orapt install default-jre              # version 2:1.11-72build2apt install openjdk-17-jre-headless  # version 17.0.8.1+1~us1-0ubuntu1~22.04apt install openjdk-18-jre-headless  # version 18.0.2+9-2~22.04apt install openjdk-19-jre-headless  # version 19.0.2+7-0ubuntu3~22.04apt install openjdk-8-jre-headless   # version 8u382-ga-1~22.04.1 Now, install the OpenJDK package: sudo apt install default-jre After installation, verify the JRE presence: java -version You should see: openjdk version "11.0.23" 2024-04-16OpenJDK Runtime Environment (build 11.0.23+9-post-Ubuntu-1ubuntu122.04.1)OpenJDK 64-Bit Server VM (build 11.0.23+9-post-Ubuntu-1ubuntu122.04.1, mixed mode, sharing) To compile and run even specific applications, you will also need the JDK package: sudo apt install default-jdk Verify the compiler version: javac -version You should see: javac 11.0.23 Installing Oracle JDK In some cases, you may need the Oracle JDK package. This installation of Java on Ubuntu will differ from the methods described above, as it requires manual installation. You cannot install it from Ubuntu repositories using apt-get install, but the process is still relatively easy. The latest version is Java 22. However, Java 21 has the longest support. We will install Java 21 in Ubuntu using wget and a download link copied from the Downloads section on the Oracle website. Run: wget https://download.oracle.com/java/21/latest/jdk-21_linux-x64_bin.deb Now install: sudo apt install ./jdk-21_linux-x64_bin.deb Check the Java version: java -version You should see: java version "21.0.3" 2024-04-16 LTSJava(TM) SE Runtime Environment (build 21.0.3+7-LTS-152)Java HotSpot(TM) 64-Bit Server VM (build 21.0.3+7-LTS-152, mixed mode, sharing) Managing Java Versions You can install multiple versions of Java on a single machine. To see the default version, use: sudo update-alternatives --config java If you've installed the previously mentioned versions, you will see: Enter the desired version number or press Enter to keep the current settings (indicated by an asterisk). This also applies to other modules like the compiler javac, keytool, javadoc, jarsigner, etc.: sudo update-alternatives --config javac Setting the JAVA_HOME Variable Most Java applications use the JAVA_HOME environment variable to determine the installation directory.  In the previous chapter, we run this command: sudo update-alternatives --config java Check the paths in its output. In our case, the directories are: OpenJDK 11: /usr/lib/jvm/java-11-openjdk-amd64/bin/java OpenJDK 8: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java Oracle Java 21: /usr/lib/jvm/java-8-oracle/jre/bin/java Copy the desired path and edit the /etc/environment file with nano: sudo nano /etc/environment Add a new line with the copied path: JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64/bin/" This sets the JAVA_HOME variable for all user accounts. Save and exit the file, then reload the environment variables: source /etc/environment Check if the changes were applied: echo $JAVA_HOME You should see: /usr/lib/jvm/java-11-openjdk-amd64/bin/ This change applies to the current user, while others need to restart the system. Conclusion We have covered the installation of Java in Ubuntu, including standard JRE/JDK versions and official Oracle releases. After installing the platform, you can use Java applications and dependencies without restrictions.
09 July 2024 · 4 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support