# JAVA for DevOps Engineer (One Stop Solution)

Java is a **hybrid of both Compiled and Interpreted language**, also it’s not an Interpreted language like JavaScript or Python. Here we use the **Build tool** to build Java applications so that we can deploy and manage them properly.

We will cover why Java is a hybrid of both compiled and interpreted language in a bit.

> ⭐Java is platform-independent but not JVM is...
> 
> Because <mark>“write once, run anywhere”</mark> concept only works on bytecode which is produced by **Java compiler**. However, platforms like Windows, macOS, Linus have its own version of JVM. So, Java maintains platform independence through its bytecode only.

## How does Java work?

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1727456355679/7da153c8-490c-487c-b971-916d21abbd2f.png align="center")

1\. **Writing the Java Code:**

* The developer writes source code in **Java** typically using a `.java` file.
    
* It is a **human-readable** code that follows the syntax of the programming language for Java.
    

2\. **Compile to Bytecode:**

* Following the writing of code, it must be compiled. There is a tool called the **Java Compiler (javac)** that accepts the human readable `.java` file and changes it into bytecode.
    
* **Bytecode** is a low-level, platform-independent representation of code that's stored in `.class` files
    

3\. **Execution - Java Virtual Machine** (JVM):

* The compiled bytecode doesn’t run directly on the hardware like fully compiled languages (C, C++).
    
* Instead, it **interprets** the bytecode into machine code and executes the application.
    

> ⭐That’s why JAVA is called as the hybrid of Compiled and Interpreted language.

---

## JDK vs JRE vs JVM

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1727442073740/5560af9f-d4b4-4829-9249-dc2b8da2f143.png align="center")

### **JDK**:

* It is a whole **software development kit** used to write, compile, and debug Java applications.
    
* Includes JRE (Java Runtime Environment) + development tools (like compilers and debuggers).
    

### **JRE**:

* The JRE provides everything needed to **run** the Java application like libraries and other dependencies, but not to **develop** them.
    
* Contains JVM (Java Virtual Machine) + core libraries and other components to run Java applications.
    

### **JVM**:

* This is the **engine** that runs our Java applications.
    
* Takes the bytecode and translates it into **machine** code for execution.
    

So, to develop an application JDK is a must-have component. If we need to run a Java application, then we can use JRE alone.

---

## Why do we need a `application.properties` file?

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1727444059886/4b7b8f00-e78b-44d1-b9fb-eeb7fb5e244b.png align="center")

* Application configurations are usually done through an `application.properties` or an `application.yml` files.
    
* Especially for applications coded with frameworks such as **Spring Boot**, the **configuration settings** of such applications like ports, and database connection strings are stored using this.
    

**Example**:

```java
# application.properties
server.port=8081

# Database settings
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=pass12
```

---

## Use of Java Build Tools?

* **Java build tools** are important in managing the complexities of building, packaging, testing, and deploying a Java application.
    
* Build tools such as **Maven**, **Gradle**, and **Ant** automatically make these processes consistent and efficient throughout the entire lifecycle of software development.
    

---

## What is `pom.xml` & `build.gradle` files?

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1727443449179/799e1663-c1aa-407a-9a0d-658387f73b22.png align="center")

These `pom.xml` (used with **Maven**) and `build.gradle` (used with **Gradle**) are configuration files essential for managing dependencies, building, and packaging our code.

### What’s in `pom.xml` (for Maven)?

The **Project Object Model (POM)** file is an XML file that defines the configuration of a Maven project.

#### Key Sections of `pom.xml`:

1. **Project Information**:
    
    * Here it defines the project's metadata like name, version, description, etc.
        
    
    ```java
    <project>
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.example</groupId>
      <artifactId>myapp</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>jar</packaging>
    </project>
    ```
    
2. **Dependencies**:
    
    * Dependencies are used to list external libraries (dependencies) that our project needs. Maven will automatically download these libraries from the **Maven Central Repository** or another repository.
        
    
    ```java
    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
      </dependency>
    </dependencies>
    ```
    
3. **Build Configuration**:
    
    * Here we need to mention the details how to build the project, including **plugins** for compiling, testing, packaging, etc.
        
    
    ```java
    <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.1</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
        </plugin>
      </plugins>
    </build>
    ```
    
4. **Repositories**:
    
    * It specifies where Maven should look for dependencies if they are not found in the Maven Central Repository.
        
    
    ```java
    <repositories>
      <repository>
        <id>my-repo</id>
        <url>https://my.repo.url</url>
      </repository>
    </repositories>
    ```
    
5. **Profiles**:
    
    * Profiles are used to configure builds for different environments, like production or development.
        
    
    ```java
    <profiles>
      <profile>
        <id>prod</id>
        <build>
          <!-- Prod specific config -->
        </build>
      </profile>
    </profiles>
    ```
    

### **What’s in** `build.gradle` (for Gradle)?

Gradle uses a **DSL (Domain Specific Language)**, and `build.gradle` files can be written in **Groovy** or **Kotlin**. They are generally more concise and flexible than `pom.xml`.

#### Key Sections of `build.gradle`:

1. **Plugins**:
    
    * It defines the plugins that extend Gradle's functionality. For example, the `java` plugin helps in building Java projects.
        
    
    ```java
    plugins {
      id 'java'
    }
    ```
    
2. **Dependencies**:
    
    * Similar to Maven, this section manages the external libraries of our project needs. Gradle can fetch these libraries from repositories like **Maven Central**.
        
    
    ```java
    dependencies {
      implementation 'org.springframework.boot:spring-boot-starter-actuator'
      testImplementation 'org.testcontainers:junit-jupiter'
    }
    ```
    
3. **Repositories**:
    
    * Here it specifies where Gradle should look for dependencies. By default, Gradle uses Maven Central.
        
    
    ```java
    repositories {
      mavenCentral()
    }
    ```
    
4. **Build Script**:
    
    * In this, we need to mention how our project should be built. We can add tasks for compilation, packaging, running tests, etc.
        
    
    ```java
    tasks.register('hello') {
      doLast {
        println 'Hello, World!'
      }
    }
    ```
    
5. **Custom Tasks**:
    
    * Here we have a custom feature that allows us to define custom tasks to automate specific actions, giving it more flexibility than Maven in certain aspects.
        
    
    ```java
    task customTask {
      doLast {
        println 'Running custom task!'
      }
    }
    ```
    
6. **Project Information**:
    
    * We can specify project details like `group`, `version`, etc., similar to `pom.xml`.
        
    
    ```java
    group = 'com.example'
    version = '1.0-SNAPSHOT'
    ```
    
7. **Build Configuration**:
    
    * We can configure how to compile and package the project, including specifying Java versions, adding plugins, and more.
        
    
    ```java
    compileJava {
      sourceCompatibility = '1.8'
      targetCompatibility = '1.8'
    }
    ```
    

---

## Logging:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1727458484833/8dd57d82-c52a-485b-a9d3-a8d81cbc24d7.png align="center")

* Java applications typically use logging frameworks like **Log4j**, **SLF4J**, or **Logback**.
    
* Why because **Logging Frameworks** provide **more flexible configurations** comparing build-in logging and frameworks give more advantages in logging format, optimized for performance and fine-grained control over log levels.
    

---

## Difference between War and Jar files:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1727459522799/5c019361-0a92-4a12-81f7-9f9fb3f5d055.png align="center")

### **JAR (Java Archive)**:

* JAR files are primarily used to package **Java applications**, libraries, or resources.
    
* Contains only compiled `.class` files and resources.
    
* Typically **deploy or execute directly** with the `java -jar` command.
    
* **Example**: A desktop application, **API** application or a library like `spring-core.jar`.
    

### **WAR (Web Application Archive)**:

* WAR files are specifically used to package **Java web applications**.
    
* Contains **everything needed for a web application**, including `.class` files, JSP pages, HTML, CSS, JS, and configuration files like `web.xml`.
    
* Deploy `myapp.war` to Tomcat by copying it to `/path/to/tomcat/webapps/`
    
* **Example**: A web-based application or service like `myapp.war` running on a Tomcat server.
    

---

## Version Manager of Java:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1727459439054/210671cf-2481-4603-8de3-ea3040bc968e.png align="center")

* A **version manager** is a tool that allows us to easily install, manage, and **switch between** **different versions** of programming languages, frameworks, or tools.
    
* **SDKMAN:** Tools that help manage multiple versions of Java, SDK and frameworks on our system.
    

> SDKMAN supported platforms: Linux, macOS, WSL (Windows subsystem for Linux).

**Example:**

* Install a specific version:
    
    ```java
    sdk install java 11.0.11-open
    ```
    
* Switch to a different version:
    
    ```java
    sdk use java 8.0.292-open
    ```
    
* List all available SDKs and their versions:
    
* ```java
            sdk list
    ```
    

---

## Containerizing the Java application:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1727459712868/98f07540-090f-437d-a06f-82d89cc10811.png align="center")

### **JAR (Java Archive)**:

1. Why **JDK** image because it includes all the tools required for compiling and packaging Java applications.
    
2. Copies all the files into the container directory.
    
3. Then clean and build the Java application based on the `pom.xml`
    
4. Use the **JRE** image for the runtime stage, because we already built the JAR file also it can run the application without JDK.
    
5. Set the working directory in the container to `/app`
    
6. Now copy the built JAR file from the build stage
    
7. This line indicates that the application will listen on port 8080. This does not publish the port.
    
8. It executes the Java application using the `java.jar` file
    

**Dockerfile:**

```dockerfile
FROM techiescamp/jdk-17:1.0.0 AS build

# Copy the Java Application source code
COPY . /usr/src/

# Build Java Application
RUN mvn -f /usr/src/pom.xml clean install -DskipTests

FROM techiescamp/jre-17:1.0.0
WORKDIR /app

# Copy the JAR file from the build stage (/app)
COPY --from=build /usr/src/target/*.jar ./java.jar

# Expose the port the app runs on
EXPOSE 8080

# Run the jar file
CMD ["java", "-jar", "java.jar"]
```

### **WAR (Web Application Archive)**:

1. Why **Tomcat** image because it contains a pre-configured Tomcat server, which is used to run Java web applications.
    
2. Remove any default web applications that come pre-installed with the Tomcat image.
    
3. Now copy all the files into the container directory.
    
4. This line indicates that the application will listen on port 8080. This does not publish the port.
    
5. No CMD is needed since the base image already has a CMD instruction
    

```dockerfile
# Use Tomcat base image
FROM tomcat:9.0

# Remove the default web apps
RUN rm -rf /usr/local/tomcat/webapps/*

# Copy the WAR file into the Tomcat webapps directory
COPY target/myapp.war /usr/local/tomcat/webapps/

# Expose the port on which Tomcat listens
EXPOSE 8080

# No CMD is needed since the base image already has a CMD instruction
```

---

Thanks for sticking with me until the end! 😊

I know it was a lengthy read, but I hope you found it valuable and worth your time. If you have any suggestions, ideas, or thoughts to add, feel free to drop them in the comments. 👇📩

Your feedback means a lot! Don’t forget to hit that like❤️ button to show your support, and stay tuned for more content. 🔔

⭐Thanks again!

#getintokube #getintokubeblogs
