Gradle – Hello World

Introduction

This tutorial is focused on writing a very simple java program and executing it using the gradle build file. Other option could be to create a gradle project using eclipse but we are not looking into that here. We just want to see how to write a build file to run a java program.

This tutorial should help you understand how to use a build file to maintain(compile, run, test etc) your code using a build file. In our day to day development we rely on IDEs like eclipse for these things but what happens when we release our code to production servers. There will be no eclipse to execute the code for us or what if in our development team not everyone is using eclipse? In such situations build files come in handy which can be run directly via the console.

Java Project

Create a java project using your preferred IDE and method. Though, a simple java file is also ok for this tutorial but creating a project will also help you understand how to add the gradle build file to any of your existing projects.

HelloWorld.java

A simple java program which prints “Hello Gradle!” to the console. Notice the package statement, this will be useful while writing the build file.

build.gradle

No need to add commonly used apply plugin: ‘java’because ‘application’ plugin implicitly adds java plugin.

Gradle assumes a default project layout and will only look into the specific directories to compile/run your project. If you have not created a project in accordance with the table below, you need to configure the project layout by configuring the appropriate source set as shown in the build above.

In our case we just have a single java file, so we are just specifying srcDirs our SourceSets.

 

Default Directory Structure

You can follow the default directory structure specified by gradle to avoid worrying about configuring your source sets but in case of existing projects sourceSet configuration can really come handy.

Table 47.4. Java plugin – default project layout

Directory Meaning
src/main/java Production Java source
src/main/resources Production resources
src/test/java Test Java source
src/test/resources Test resources
src/sourceSet/java Java source for the given source set
src/sourceSet/resources Resources for the given source set

 

Execution

Go to the directory where your build.gradle is stored in your local file system.
The ‘application’ plugin we applied as the first line of our build file adds implicit run task for executing our code. On the command prompt just type:

and you should see the output as:

Further Reading

https://docs.gradle.org/current/userguide/java_plugin.html