Overview
Gradle is a build tool for Java.
Example Project
The following steps create a simple Java project that can be built using Gradle.
-
Install SDKMAN!.
-
Install Gradle by entering
sdk install gradle 8.8 -
Create a directory for the project.
-
Create the file
build.gradle, which uses Groovy, in the project directory containing the following:plugins { id 'application' id 'java' } application { // applicationDefaultJvmArgs = ['-Dgreeting.language=en'] mainClass = 'HelloWorld' } java { sourceCompatibility = JavaVersion.VERSION_18 } repositories { mavenCentral() } dependencies { // Add dependencies here if needed } -
Inside the project directory, create the diretory
src/main/java. -
Create the file
src/main/java/HelloWorld.javacontaining the following:public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } -
To build the project, enter
gradle buildThis creates the
buildsubdirectory if it doesn’t exist and it writes all generated files inside that directory. -
To run the project, enter
gradle runThis will also build the project before running if it has not been built or if source files have been modified since the last build. So it is never necessary to run
gradle build. -
To delete all the generated files (the
builddirectory), entergradle clean.
Kotlin
The following file build.gradle.kts is nearly identical to the build.gradle file above, but it uses Kotlin instead of Groovy.
plugins {
// The "java" and "application" plugins are special.
// All other plugins must use the syntax `id("plugin.id")`.
id 'application'
id 'java'
}
application {
applicationDefaultJvmArgs = ['-Dgreeting.language=en']
mainClass = 'HelloWorld'
}
java {
sourceCompatibility = JavaVersion.VERSION_18
}
repositories {
mavenCentral()
}
dependencies {
// Add dependencies here if needed
}