Java Gradle Basics
In this page:
What is Gradle?
Gradle is a modern build automation tool for Java (and other languages) that uses a programmable build script instead of a fixed XML format, offering more flexibility and generally faster incremental builds than Maven.
Example: What is Gradle?
public class Main {
public static void main(String[] args) {
System.out.println("Gradle uses a programmable build script instead of fixed XML");
}
}
Login to try C/C++/Java/PHP code in the editor
The build.gradle File
A Gradle project is configured through a build.gradle (or build.gradle.kts) file, which applies plugins like java to add standard tasks, declares repositories to search for dependencies, and lists the project's dependencies.
Example: The build.gradle File
public class Main {
public static void main(String[] args) {
String buildScript = "plugins { id 'java' }\nrepositories { mavenCentral() }\ndependencies { implementation 'com.example:lib:1.0' }";
System.out.println(buildScript);
}
}
Login to try C/C++/Java/PHP code in the editor
Gradle Tasks
Gradle organizes work into tasks, such as compileJava, test, and build, and tasks can depend on each other so that running one automatically triggers the tasks it needs first, similar to Maven's lifecycle phases.
Example: Gradle Tasks
public class Main {
public static void main(String[] args) {
String[] tasks = {"compileJava", "test", "build"}; // build depends on test, which depends on compileJava
for (String t : tasks) System.out.println(t);
}
}
Login to try C/C++/Java/PHP code in the editor
Kotlin DSL vs Groovy DSL
Gradle build scripts can be written in Groovy DSL (build.gradle), which is dynamically typed and concise, or Kotlin DSL (build.gradle.kts), which is statically typed and gives stronger IDE support and compile-time checking.
Example: Kotlin DSL vs Groovy DSL
public class Main {
public static void main(String[] args) {
String groovy = "build.gradle (Groovy, dynamically typed)";
String kotlin = "build.gradle.kts (Kotlin, statically typed)";
System.out.println(groovy + " vs " + kotlin);
}
}
Login to try C/C++/Java/PHP code in the editor
Gradle vs Maven
Gradle and Maven solve the same core problem -- compiling, testing, and packaging a project along with its dependencies -- but Gradle's script-based configuration is generally more flexible and its incremental build caching tends to be faster.
Example: Gradle vs Maven
public class Main {
public static void main(String[] args) {
System.out.println("Both compile/test/package; Gradle's caching tends to be faster");
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: