---
title: "Jam 04 - Exercise 1"
tags:
- 4 🥳 done
- jam04
- gradle
- build tools
---
<!-- markdownlint-disable line-length single-h1 no-inline-html -->
<!-- markdownlint-configure-file { "ul-indent": { "indent": 4 }, "link-fragments": {"ignore_case": true} } -->
{%hackmd dJZ5TulxSDKme-3fSY4Lbw %}
# Exercise 1 – Setting up Gradle
## Overview - Exercise 1
In this exercise, you'll configure Gradle as your build automation tool. Gradle is an industry-standard build tool that helps manage dependencies, compile code, run tests, and package applications. Setting up Gradle now will make future development tasks much easier and prepare you for professional Java development practices.
:::info
🔑 **Key Concepts**
- Build automation tools like Gradle are essential for modern software development
- Proper project structure is crucial for maintainable code
- Build scripts define how your project is compiled and run
:::
## Required Steps
### Step 1 – Create Module Info
1. In IntelliJ, create a new `module-info.java` file in the `src/main/java` directory (It's important that this file is in the `src/main/java` directory, not in the root of the project and that the file is named `module-info.java` with a hyphen, not an underscore.)

2. Open the file and update the contents to show the following:
```java
module csci205_jams {
// requires javafx.controls;
// requires javafx.fxml;
}
```
3. Close IntelliJ. <!-- markdownlint-disable ol-prefix -->
:::danger
🚨 It is important that you keep IntelliJ closed until after gradle setup files have been added (after the `scp command`)
:::
:::info
🔧 **Notes**:
1) The commented lines will be used later when we add JavaFX to our project.
2) The default module will appear as `csci205.jams`. You need to update this to `csci205_jams`.
:::
### Step 2 – Verify Gradle Installation
1. Close IntelliJ before proceeding with the Gradle setup steps. This will prevent any potential conflicts and ensure a clean initialization process.
2. Open your terminal (or git bash for windows) and run:
```bash
gradle -v
```
You should see output showing your Gradle version and build time information (your version might vary slightly).
```bash
------------------------------------------------------------
Gradle 8.12.1
------------------------------------------------------------
Build time: 2025-01-24 12:55:12 UTC
Revision: 0b1ee1ff81d1f4a26574ff4a362ac9180852b140
// more information...
```
:::warning
🚨 **Common Issue**: If Gradle is not found, go back to jam00 and follow the instructions there.
:::
### Step 3 – Set Up Gradle Project
:::warning
⚠️ **CRITICAL**:
1) It is absolutely essential that you run the Gradle setup commands from the root of your project directory. Running it from a subdirectory will create an incorrect project structure that will be difficult to fix later.
2) It is important that you follow these instructions exactly. Selecting the wrong options will result in a project structure that will not work. It can be challenging to correct a gradle initialization gone wrong.
:::
1. Use `pwd` to verify you are in the root of your project:
```bash
pwd
```
The output should show the full path ending with `csci205_jams`. If you're in a subfolder (like `src` or `build`), use `cd` to navigate until you're in the project root.
2. Run the Gradle initialization:
```bash
gradle init
```
:::warning
🚨 **Important**: You may see this prompt:
```text
Found existing files in the project directory: '/path/to/csci205_jams'.
Directory will be modified and existing files may be overwritten. Continue? (default: no) [yes, no]
```
Type `yes` and press ENTER. This will set up the necessary Gradle files in your project. While we already have a `.gitignore`, we want Gradle to add its configuration files.
:::
3. When prompted, select (your order may vary but the answers remain the same):
- Type of project: Basic
- Project name: Press ENTER (to use the default)
- Build script DSL: Groovy
- Generate build using new APIs: Press ENTER (defaults to no)
4. Get the class configuration files:
🚨 Remember to replace `userid` with your bucknell username.
```bash
# If working on your laptop use these two commands (replace userid with your bucknell username):
scp "userid@linuxremote.bucknell.edu:/home/csci205/2025-spring/student/build.gradle" "build.gradle"
scp "userid@linuxremote.bucknell.edu:/home/csci205/2025-spring/student/gitignore" ".gitignore"
# If working on linuxremote:
cp "/home/csci205/2025-spring/student/build.gradle" "build.gradle"
cp "/home/csci205/2025-spring/student/gitignore" ".gitignore"
```
:::info
💡 This will ensure you have:
1. The most up-to-date version of the class `.gitignore` file with all necessary Gradle-related exclusions
2. The correct `build.gradle` configuration for the course
:::
### Step 4 – Configure Build Script
:::danger
🚨 It is now safe to reopen IntelliJ
:::
1. When you reopen IntelliJ, you should see a notification about loading the Gradle project:
- Look for a notification at the bottom that says "Gradle build script file has changed"
- Click "Load" in that notification

- You'll know it worked when you see the Gradle tool window appear on the right side of IntelliJ.

2. Locate `build.gradle` in the Project Explorer. Double-click to open it and update the group line:
```groovy
group = 'org.xyz' // Replace xyz with your initials
```
### Step 5 – Explore Gradle Tasks
Gradle organizes its functionality into **tasks** - these are the building blocks that make up your build process. Each task represents a piece of work Gradle can perform on your project, such as:
- Compiling your code
- Running your tests
- Creating documentation
- Packaging your application
- And much more!
Understanding these tasks is crucial because they form the foundation of how you'll work with your Java projects. Instead of manually managing compilation, dependencies, and execution, Gradle automates these processes through these predefined tasks.
Throughout this semester, we'll gradually introduce and use different Gradle tasks as they become relevant to your work:
- We'll start with basic tasks like `build` and `run` for compiling and running your programs
- As we begin writing tests, you'll learn to use the `test` task to verify your code
- When we start working with external libraries, you'll use tasks to manage dependencies
- By the final project, you'll be comfortable using Gradle to manage complex project builds
:::warning
🚨 **First Time Running Gradle**
The first time you run any Gradle command, it will take longer than usual because Gradle needs to:
- Download all the libraries you'll need for the course
- Set up its local cache in a hidden folder (`~/.gradle` in your home directory)
- Configure your project's build environment
Don't worry if it seems slow initially - subsequent runs will be much faster!
:::
For now, let's explore the basic tasks available to us:
1. Let's see what tasks are available. In your terminal, run:
```bash
./gradlew tasks
```
This will show all available Gradle tasks.
:::spoiler 📋 Click here to see the full Gradle tasks output 🔍
```text
$ ./gradlew tasks
> Configure project :
Project : => 'csci205_jams' Java module
> Task :tasks
------------------------------------------------------------
Tasks runnable from root project 'csci205_jams'
------------------------------------------------------------
Application tasks
-----------------
run - Runs this project as a JVM application
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the classes of the 'main' feature.
testClasses - Assembles test classes.
Build Setup tasks
-----------------
init - Initializes a new Gradle build.
updateDaemonJvm - Generates or updates the Gradle Daemon JVM criteria.
wrapper - Generates Gradle wrapper files.
Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.
Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the 'main' feature.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'csci205_jams'.
dependencies - Displays all dependencies declared in root project 'csci205_jams'.
dependencyInsight - Displays the insight into a specific dependency in root project 'csci205_jams'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'csci205_jams'.
projects - Displays the sub-projects of root project 'csci205_jams'.
properties - Displays the properties of root project 'csci205_jams'.
resolvableConfigurations - Displays the configurations that can be resolved in root project 'csci205_jams'.
tasks - Displays the tasks runnable from root project 'csci205_jams'.
IDE tasks
---------
cleanIdea - Cleans IDEA project files (IML, IPR)
idea - Generates IDEA project files (IML, IPR, IWS)
openIdea - Opens the IDEA project
Verification tasks
------------------
check - Runs all checks.
test - Runs the test suite.
Rules
-----
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.
To see all tasks and more detail, run gradlew tasks --all
To see more detail about a task, run gradlew help --task <task>
BUILD SUCCESSFUL in 428ms
1 actionable task: 1 executed
```
:::
2. In IntelliJ, open the Gradle tool window (View → Tool Windows → Gradle, or click the Gradle icon in the left sidebar) to see the same tasks graphically.
:::info
🔑 **Key Tasks to Know**
Here are the most important tasks you'll use regularly:
- `build` - Compiles your code and runs tests
- `run` - Executes your application
- `clean` - Removes all compiled files (useful when you want a fresh start)
- `test` - Runs your test suite
- `check` - Performs all verification tasks including tests
These tasks form the core of your development workflow. For example:
1. Make changes to your code
2. Run `build` to ensure everything compiles
3. Use `run` to test your changes
4. If something's not working, use `clean` and then `build` to start fresh
:::
### Step 6 – Test Your Setup
The `build` task is fundamental to your Java development workflow. When you run `build`, Gradle will compile ALL your Java files into `.class` files, but with a key advantage: it keeps your source tree clean by storing all compiled files in a separate `build` directory. This is why we created that `build` folder back in jam00!
But here's an interesting question: how does Gradle know which program to run when you have multiple main methods in different classes?
Open your `build.gradle` file and scroll to the bottom. You'll see something like this:

This `mainClass` setting tells Gradle which class contains the main program you want to run. Right now it's set to run the `PrimitivePerf` program from `jam02`. You'll change this later when you want to run different programs.
Let's try building your project:
1. Run the build command:
```bash
./gradlew build
```
:::warning
🚨 **Important Notes**:
- If you have ANY errors in ANY of your Java files in the project, the build will fail
- This includes ALL files in your ENTIRE project, even from previous jams
- Common issues that cause build failures:
- Syntax errors
- Missing semicolons
- Incorrect method signatures
- Unresolved dependencies
- Compilation errors in old files from previous jams
- Check the error messages carefully - they will point you to the specific files and lines that need fixing
- You must fix ALL errors before the build can succeed
- The first build might take some time as Gradle downloads necessary dependencies
:::
2. When the build succeeds, you'll see something like:
```text
BUILD SUCCESSFUL in 2s
5 actionable tasks: 5 executed
```
Don't worry about the exact times or number of tasks - just focus on getting that "BUILD SUCCESSFUL" message!
After a successful build, Gradle organizes your compiled files into the `build` directory:
- `classes`: Your compiled `.class` files
- `libs`: JAR files (Java Archives) of your project
- `tmp`: Temporary files used during compilation
- `reports`: Test and other reports (when you add tests later)
This separation of source code and compiled files is a software development best practice!
3. Now let's run our first program. The basic command is:
```bash
./gradlew run
```
This command will run whatever program is specified as the `mainClass` in your `build.gradle` file. Right now, that should be the `PrimitivePerf` program from `jam02`. When you run it, you should see your PrimitivePerf output, confirming that:
- Your code compiled successfully
- Gradle found the correct main class
- The program can run without errors
4. What if you want to run a different program?
As you create more programs with main methods, you'll need to know how to run specific ones. There are two ways to do this (beyond the IntelliJ run buttons ▶️):
- **Update build.gradle and use `run`**:
Open your `build.gradle` file and update the `mainClass` setting to run a different java file you have in your project:
```groovy
application {
mainClass.set('jam01.HelloWorld') // Currently set to run jam02.PrimitivePerf, change this!
}
```
Then run your program:
```bash
./gradlew run --console=plain
```
:::warning
🚨 **Important**: The `--console=plain` flag is crucial when running programs that need user input. Without it, Gradle's progress output can interfere with your program's input prompts.
:::
- **Run directly without editing build.gradle**:
You can run any main program by specifying the class name on the command line:
```bash
./gradlew run -PmainClass=jam02.Die --console=plain
```
This approach is convenient when testing multiple programs without editing build files.
:::info
💡 **Working with Gradle**
There are two ways to work with Gradle:
**Command Line**
- `build` compiles your code and creates the necessary files
- `run` executes your program
- You need to `build` again after code changes
- You can `run` multiple times without rebuilding if no changes
**IntelliJ Integration**
- The Gradle tool window shows all available tasks
- Underneath Tasks and application, double-click tasks to run them
- IntelliJ automatically detects changes and prompts rebuilds
- The green "Run" button (▶️) handles building and running automatically
We're using the command line now to understand the concepts, but you'll use IntelliJ's features more as you get comfortable with Gradle.
:::
> 🔍 **Checkpoint**
>
> - Gradle is properly installed and configured
> - `module-info.java` is created in the correct location
> - Build script is updated with your initials
> - Project builds successfully with `./gradlew build`
## Save Your Work - Exercise 1
Stage known changes:
```bash
git add .gitattributes .gitignore build.gradle gradle/ gradlew gradlew.bat settings.gradle src/main/java/module-info.java .idea/
```
Verify what files are uncommitted:
```bash
git status
```
If you have any remaining "Changes not staged for commit" or "Untracked files", understand why. In most cases, you should not have any uncommitted changes. However, maybe you have some changes to previous jams that should have been committed. You should understand every file that is "red" and understand why it is red.
Commit your work:
```bash
git commit -m "jam04: Configure Gradle build system"
```
Your working directory should now be clean.
:::success
🔑 **Key Takeaway**: You've now set up a professional-grade build system that will help manage your Java projects throughout the course and in your future career.
:::