Skip to main content

Hello World (first programs) · Beginner · 15 min

Hello World in Groovy: scripts, closures and where you meet them

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Apache Groovy 6.0.0 · Eclipse Temurin JDK 25

You will install Apache Groovy 6.0 on JDK 25, run Hello World as a one-line script and in groovysh, write a script that uses a closure, GString interpolation and command-line arguments, and read a Jenkinsfile and a Gradle build script line by line.

On this page

Groovy is a language for the Java Virtual Machine (JVM). Like Java and Kotlin, it compiles to JVM bytecode, runs on the same java runtime and can use any Java library directly. What makes it different is how much it lets you leave out. A Groovy file can be a plain script with no class and no main method, types are optional, and most Java code is also valid Groovy, so a Java programmer can start writing Groovy without learning new syntax first and drop the ceremony bit by bit.

Groovy is dynamic by default: it decides many things, such as which method a call reaches, while the program runs rather than when it is compiled. That flexibility is why it became the language of two tools you will probably meet before you choose to write Groovy yourself: Jenkins pipelines and Gradle build scripts.

In this tutorial you install Groovy 6.0 from the Apache release, run Hello World as a script and in the interactive shell, look at what the compiler turns your script into, and write a script with a closure, string interpolation and command-line arguments. You finish by reading a Jenkinsfile and a Gradle build script line by line, so they stop looking like magic.

Step 1 · Check that JDK 25 is installed

Groovy runs on the JVM, so you need a JDK first. Groovy 6 needs JDK 17 or newer; this tutorial uses JDK 25, the current long-term support release. If you do not have it, follow the first step of Hello World in Java, which installs Eclipse Temurin JDK 25 from the Adoptium apt repository. Then check it:

Bash
java -version

Check it worked

The first line starts with something like openjdk version "25.0.5". Any JDK 25 patch release works. If you see command not found, install the JDK before going on.

Step 2 · Install Groovy 6.0

The Apache Groovy project publishes each release as a zip file with a SHA-256 checksum beside it. The zip is about 50 MB, so if you are on prepaid mobile data, download it once over Wi-Fi and keep a copy. Install curl and unzip, download both files into a fresh temporary folder, and check the zip:

Bash
sudo apt update
sudo apt install -y curl unzip ca-certificates
GROOVY_VERSION=6.0.0
cd "$(mktemp -d)"
curl -fsSLO "https://dlcdn.apache.org/groovy/${GROOVY_VERSION}/distribution/apache-groovy-binary-${GROOVY_VERSION}.zip"
curl -fsSLO "https://dlcdn.apache.org/groovy/${GROOVY_VERSION}/distribution/apache-groovy-binary-${GROOVY_VERSION}.zip.sha256"
echo "$(tr -d '\r\n' < "apache-groovy-binary-${GROOVY_VERSION}.zip.sha256")  apache-groovy-binary-${GROOVY_VERSION}.zip" | sha256sum -c -

The .sha256 file holds only the hash, ending in a Windows line break. tr -d '\r\n' strips that, and the echo adds the file name in the format sha256sum -c expects. The last line must print apache-groovy-binary-6.0.0.zip: OK. If it prints FAILED, stop, delete the files and download again.

Unpack Groovy into a folder in your home directory and put its bin folder on your path:

Bash
mkdir -p ~/.local/opt
unzip -q "apache-groovy-binary-${GROOVY_VERSION}.zip" -d ~/.local/opt
export PATH="$HOME/.local/opt/groovy-${GROOVY_VERSION}/bin:$PATH"
echo "export PATH=\"\$HOME/.local/opt/groovy-${GROOVY_VERSION}/bin:\$PATH\"" >> ~/.bashrc
groovy --version

The zip contains a folder called groovy-6.0.0, and its bin folder holds the groovy, groovyc and groovysh launch scripts. The export line makes them work in this shell, and the line added to ~/.bashrc does the same for every new terminal.

A copy of Groovy you unpack yourself gets no updates from apt. To upgrade, repeat this step with a newer GROOVY_VERSION, change the version in the line at the end of ~/.bashrc, and delete the old folder. When a newer version comes out, older ones move from dlcdn.apache.org to archive.apache.org/dist/groovy/, so use that address if a download of 6.0.0 returns 404.

SDKMAN, a version manager for JVM tools, installs the same release with sdk install groovy 6.0.0 and lets you switch versions later. On macOS, brew install groovy works. On Windows, unzip the same file and add its bin folder to PATH in the system settings.

Check it worked

groovy --version prints something like Groovy Version: 6.0.0 JVM: 25.0.5 Vendor: Eclipse Adoptium OS: Linux. It takes a second or two, because a JVM has to start first.

Step 3 · Write Hello World as a script

Make a throwaway folder and create hello.groovy in it. The whole program is one line:

Bash
mkdir -p ~/hello-groovy-demo
cd ~/hello-groovy-demo
cat > hello.groovy <<'GROOVY'
println "Hello, World!"
GROOVY
groovy hello.groovy

Compare that with the five lines Java needs. Here is what Groovy lets you drop:

  • No class and no main method. Statements at the top level of a file make a script, and Groovy runs them from top to bottom.
  • No System.out. println is available everywhere in Groovy and prints the text followed by a line break.
  • No brackets around the argument. When a method call has at least one argument and stands on its own as a statement, the brackets are optional. println("Hello, World!") means the same thing.
  • No semicolon. A statement ends at the end of the line.

groovy hello.groovy compiles the file to bytecode in memory and runs it straight away. There is no separate compile step and no .class file left behind.

Check it worked

The command prints Hello, World! and nothing else, and ls shows only hello.groovy in the folder.

Step 4 · See the class Groovy builds for you

The JVM can only run classes, yet you never wrote one. Compile the script to a file with groovyc, the Groovy compiler, and look at the result with javap, the class viewer that comes with the JDK:

Bash
groovyc hello.groovy
ls
javap -cp . hello

groovyc wrote hello.class. javap shows a class called hello, named after the file, that extends groovy.lang.Script. It has a run() method holding your println line and a public static void main method that takes the command-line strings and starts it, exactly the main a Java program has. Groovy wrote that wrapper so you did not have to. It is also why a script's file name must be a valid class name: hello-world.groovy would make a class name with a hyphen in it.

Delete the class file, because the next steps run scripts directly:

Bash
rm hello.class

Check it worked

javap prints a line like public class hello extends groovy.lang.Script followed by method signatures that include main and run.

Step 5 · Try the same line in groovysh

groovysh is the Groovy shell: you type a line, press Enter and see the result at once. It is the quickest way to try something out. Start it:

Bash
groovysh

At the groovy> prompt, type these lines one at a time:

Text
println "Hello from groovysh"
1 + 2
"groovy".toUpperCase()
/exit

The first line prints the greeting. The next two show their value without println, because the shell displays the result of every expression you enter: 3, then GROOVY. Commands to the shell itself start with a slash: /help lists them and /exit leaves.

For a single line without opening the shell, pass it to groovy with -e:

Bash
groovy -e 'println "Hello from groovy -e"'

Check it worked

In groovysh, the second and third lines show 3 and GROOVY, and /exit returns you to your normal prompt. The groovy -e command prints Hello from groovy -e.

Step 6 · Add a closure, a GString and arguments

Now write a script that does a little more. Create greet.groovy:

Bash
cat > greet.groovy <<'GROOVY'
def name = args ? args[0] : 'World'

def greet = { String who -> "Hello, ${who}!" }

println greet(name)
println "Your name has ${name.length()} letters."

def languages = ['Java', 'Kotlin', 'Groovy']
languages.each { println "$it runs on the JVM" }
GROOVY
groovy greet.groovy
groovy greet.groovy Amara

Line by line:

  • def name = ... declares a variable. def means "I am not giving a type"; Groovy works out what the value is while the script runs.
  • args is the list of command-line words after the script name. Groovy gives every script this variable without you declaring it. args ? args[0] : 'World' uses Groovy truth: an empty list counts as false, so with no arguments name is 'World', and with one it is that word.
  • { String who -> "Hello, ${who}!" } is a closure: a block of code you can store in a variable, pass around and call later. Everything before -> is its parameter list, and the last expression is what it returns, so it needs no return. greet(name) calls it.
  • "Hello, ${who}!" is a GString: a double-quoted string in which ${...} is replaced by the value inside it. Single-quoted strings, like 'World', are plain Java strings, and ${} inside them stays as text.
  • ${name.length()} shows that any expression can go inside the braces, not only a variable name.
  • ['Java', 'Kotlin', 'Groovy'] is a list literal. Java needs List.of(...) or an ArrayList for the same thing.
  • languages.each { ... } calls the closure once per item. A closure with one parameter that you do not name gets it. "$it runs on the JVM" uses the short form of interpolation, a $ with no braces, which works for a plain name.

That last line is the shape you will see all over Jenkins and Gradle files: a method name followed by a closure in curly braces. When a closure is the last argument, it can sit outside the brackets, and if it is the only argument the brackets go too.

Check it worked

With no argument, the script prints Hello, World!, Your name has 5 letters. and three lines ending in runs on the JVM. With Amara, the first line is Hello, Amara!.

Step 7 · See dynamic and optional typing in action

Two claims made at the start are worth testing yourself: Java code is mostly valid Groovy, and types are optional and checked while the script runs. Create a file written entirely in Java syntax:

Bash
cat > JavaStyle.groovy <<'GROOVY'
public class JavaStyle {
    public static void main(String[] args) {
        String language = "Groovy";
        System.out.println("This Java code runs as " + language + ".");
    }
}
GROOVY
groovy JavaStyle.groovy

The semicolons, the class and System.out.println are all accepted. A few Java features behave differently in Groovy, but for everyday code like this, the same text works in both.

Now give a variable a type and break it on purpose. Create types.groovy:

Bash
cat > types.groovy <<'GROOVY'
def anything = 42
anything = 'now a string'
println "Before the mistake: ${anything}"
int count = 'five'
println 'This line never runs.'
GROOVY

Run it:

Bash
groovy types.groovy

A def variable can hold a number and then a string. int count says the value must be a whole number, and 'five' is not one. Java would refuse to compile this file. Groovy compiles it, runs the first three lines and fails only when it reaches line 4. That is the trade: quicker to write, but some mistakes surface only when that line runs. Groovy can check types at compile time too, with the @CompileStatic annotation, which large Groovy code bases use.

Check it worked

JavaStyle.groovy prints This Java code runs as Groovy. Running types.groovy prints Before the mistake: now a string, then an error that includes something like GroovyCastException: Cannot cast object 'five' with class 'java.lang.String' to class 'int', and This line never runs. does not appear.

Step 8 · Read a Jenkinsfile and a Gradle build script

Most people first meet Groovy in a file someone else wrote. You do not run these two here, because each needs its own tool installed, but with what you now know about closures you can read them.

A Jenkinsfile

Jenkins is a widely used self-hosted automation server. A project describes its pipeline in a file called Jenkinsfile, written in Groovy:

Text
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh './gradlew build'
            }
        }
    }
    post {
        always {
            echo "Finished ${env.JOB_NAME} build ${env.BUILD_NUMBER}"
        }
    }
}
  • pipeline { ... } is a call to a method named pipeline with one closure as its argument. This is the Declarative Pipeline format, and everything inside it is a set of nested method calls with closures.
  • agent any is agent(any) without brackets: run on any machine Jenkins has available.
  • stages { ... } holds the stages, and stage('Build') { ... } is one of them. The stage name is a normal argument in brackets, followed by a closure outside them.
  • steps { ... } lists what the stage does. sh './gradlew build' runs a shell command, here a Gradle build.
  • post { always { ... } } runs after the stages, whether they passed or failed.
  • "Finished ${env.JOB_NAME} build ${env.BUILD_NUMBER}" is a GString. env holds variables Jenkins sets for every run.

If you have written a GitHub Actions workflow, this is the same idea in a different language: YAML there, Groovy here.

A Gradle build script

Gradle builds Java, Kotlin and Android projects. Its build script, build.gradle, can be written in Groovy:

Text
plugins {
    id 'application'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.12.2'
}

application {
    mainClass = 'demo.App'
}
  • plugins { id 'application' } turns on Gradle's application plugin, which adds tasks to build and run a program. id 'application' is id('application') without brackets.
  • repositories { mavenCentral() } says where to download libraries from: Maven Central, the main public store of Java libraries.
  • dependencies { ... } lists libraries. testImplementation adds JUnit for tests only, so it does not ship with the program.
  • application { mainClass = 'demo.App' } sets which class holds the program's main method.

Gradle now creates new builds with a Kotlin script, build.gradle.kts, by default, so you will see both. The Groovy form above is still supported and common in existing projects and Android apps.

Check it worked

Without looking back, point to three method calls that take a closure in the Jenkinsfile, and say what id 'application' would look like with brackets. Answers: any of pipeline, stages, stage, steps, post or always; and id('application').

Step 9 · Fix the mistakes beginners hit and clean up

These come up early. Each has a known cause:

  • groovy: command not found: the bin folder is not on your path in this terminal. Open a new terminal so ~/.bashrc runs, or run the export PATH=... line again.
  • An error about JAVA_HOME or a missing java: Groovy cannot find the JDK. Check java -version first.
  • ${name} printed as text: you used single quotes. Only double-quoted strings are GStrings.
  • No such property: nmae for class: greet: a misspelt variable. Because Groovy is dynamic, this appears when the line runs, not before, and the message names the script class.
  • Ambiguous expression could be either a parameterless closure expression or an isolated open code block: a block in curly braces that Groovy cannot attach to anything, often because the opening { was moved to its own line below a call such as languages.each. Keep the opening brace on the same line as the call it belongs to.
  • Odd class-name errors from groovyc: the file name is not a valid class name. Use letters, digits and underscores, and no hyphens.

Clean up when you are done. This removes only the folder you made:

Bash
cd ~
rm -rf ~/hello-groovy-demo

Keep Groovy if you want to carry on. To remove it, delete ~/.local/opt/groovy-6.0.0 and the export PATH line you added at the end of ~/.bashrc.

Check it worked

ls ~/hello-groovy-demo reports that there is no such file or directory, and groovy --version still works in a new terminal if you kept Groovy.

Where Groovy is used

You meet Groovy mostly in build and delivery work. Jenkins pipelines, and the shared libraries teams write to reuse pipeline code, are Groovy. Many Gradle builds, including a lot of Android projects, still use the Groovy DSL. In testing, Spock is a Groovy test framework that many Java teams use for readable tests, even when the main code is Java. Grails, a web framework, is built on Groovy, and some Java applications embed Groovy so users can write scripts or rules without recompiling the program. For DevOps and platform engineers in particular, reading Groovy well enough to fix a failing pipeline is a practical skill, whether or not you ever start a Groovy project.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.