Skip to content

Instantly share code, notes, and snippets.

@AppleBoiy
Last active November 11, 2023 13:02
Show Gist options
  • Save AppleBoiy/dce79c1f257d5160c915fe91b151faa7 to your computer and use it in GitHub Desktop.
Save AppleBoiy/dce79c1f257d5160c915fe91b151faa7 to your computer and use it in GitHub Desktop.
build.gradle for simple Java program

Gradle: Build Automation Tool

NOTE This method is quite advanced and is not recommended for beginners. It uses Gradle, a build automation tool, to compile and run complex programs that consist of multiple source-code files.

Project structure:

.
├── build.gradle
└── src/
    └── main/
        └── java/
            └── com/
                └── myproject/
                    ├── Main.java
                    └── Greet.java

You can create the project structure manually or use the following command to create the project structure:

mkdir -p src/main/java/com/myproject
  1. Create a file named build.gradle and copy the following code into it:

    plugins {
        id 'java'
    }
    
    task execute(type: JavaExec, dependsOn: 'compileJava') {
        main = 'com.myproject.Main'
        classpath = sourceSets.main.runtimeClasspath
    }
    
  2. Main.java and Greet.java are located in the src/main/java/com/myproject directory.

    Main.java:

    public class Main {
        public static void main(String[] args) {
            HelloWorld.sayHello();
        }
    }

    Greet.java:

    package com.myproject;
    
    public class Greet {
        public static void sayHello() {
            System.out.println("Hello, World!");
        }
    }
  3. Run the program using the gradle command:

    gradle execute
plugins {
id 'java'
}
task execute(type: JavaExec, dependsOn: 'compileJava') {
main = 'com.myproject.Main'
classpath = sourceSets.main.runtimeClasspath
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment