> ## Documentation Index
> Fetch the complete documentation index at: https://programming-for-career.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Install Java on Ubuntu

> Learn how to install Java on Ubuntu in a few simple steps.

To **install Java** and **run Java code** in Linux (Ubuntu or other distributions), follow these steps:

## **Step 1: Install Java**

### **Option 1: Install OpenJDK (Recommended)**

#### **Check Available Java Versions**

```sh theme={null}
sudo apt update
apt search openjdk
```

#### **Install OpenJDK 17 (Recommended)**

```sh theme={null}
sudo apt install -y openjdk-17-jdk
```

To install a different version (e.g., **Java 21**), replace `openjdk-17-jdk` with `openjdk-21-jdk`.

#### **Verify Java Installation**

```sh theme={null}
java -version
javac -version
```

### **Option 2: Install Oracle JDK (If Required)**

Oracle JDK requires manual installation. Use this if OpenJDK is not suitable for your needs.

1. **Download Oracle JDK** from the [official Oracle website](https://www.oracle.com/java/technologies/javase-downloads.html).
2. Extract it and set up environment variables manually.

## **Step 2: Run Java Code**

### **Method 1: Compile and Run Java Code (Without an IDE)**

1. Create a **Java file**:
   ```sh theme={null}
   nano HelloWorld.java
   ```
2. Add the following Java code:
   ```java theme={null}
   public class HelloWorld {
       public static void main(String[] args) {
           System.out.println("Hello, World!");
       }
   }
   ```
3. Save the file (`Ctrl + X`, then `Y`, then `Enter`).
4. **Compile the Java file:**
   ```sh theme={null}
   javac HelloWorld.java
   ```
   This generates a `HelloWorld.class` file.
5. **Run the Java program:**
   ```sh theme={null}
   java HelloWorld
   ```
   Expected output:
   ```
   Hello, World!
   ```

### **Method 2: Run Java Code Using `jshell` (Interactive Mode)**

If you installed **Java 9+**, you can use `jshell` for quick testing:

```sh theme={null}
jshell
```

Then type:

```java theme={null}
System.out.println("Hello, World!");
```

Press **Enter**, and it will print:

```
Hello, World!
```

Exit `jshell` using:

```sh theme={null}
/exit
```

## **Step 3: Set JAVA\_HOME (If Needed)**

To set the `JAVA_HOME` environment variable:

```sh theme={null}
echo "export JAVA_HOME=$(dirname $(dirname $(readlink -f $(which java))))" >> ~/.bashrc
echo "export PATH=\$JAVA_HOME/bin:\$PATH" >> ~/.bashrc
source ~/.bashrc
```

Check if it’s set:

```sh theme={null}
echo $JAVA_HOME
```
