Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 38 ยท Language Basics

Groovy Syntax Basics

Learn core Groovy syntax: scripts versus classes, optional semicolons and parentheses, comments, default imports, packages, println, the power assert and method definitions.

Groovy syntax is Java syntax with the noise turned down. Once you know which parts are optional and which are not, you can read almost any Groovy program. This lesson covers the building blocks you will use in every script: how a file is organised, how statements end, how comments and imports work, and how to check your assumptions with assert.

The examples are read-only Groovy blocks (Groovy cannot run on this site) plus Java stand-ins where an idea can be shown with runnable code. Output is printed only when it is certain.

Scripts and classes

A Groovy file can hold plain statements. Groovy wraps them in a class (named after the file) with a main method, so this complete file is a program:

GROOVY
println 'Hello from a script'

A file can also define classes in the Java style, and a class can contain a static void main(String[] args). Mixing is possible: a script may declare classes and methods above or below its statements.

GROOVY
def greet(String who) {
    "Hello, $who"
}

println greet('Groovy')

The method greet returns its last expression, so no return is needed. The script prints Hello, Groovy.

Statements and semicolons

A statement ends at the end of the line. A semicolon is only needed to put two statements on one line:

GROOVY
def a = 1; def b = 2
println a + b

When an expression is not finished at the end of a line (it ends with an operator, a comma or an open bracket), the next line continues it. The reverse is the trap: a line that starts with an operator may be a new statement.

GROOVY
def total = 1 +
    2 +
    3          // fine: lines end with +
println total

Parentheses are often optional

You may drop the parentheses of a method call when it has at least one argument and the call is a statement:

GROOVY
println 'with no parentheses'
println('with parentheses')       // same thing
Math.max 3, 9                      // legal, but harder to read

Parentheses stay mandatory when the call has no arguments (list.clear()), when you use the result in an expression (def m = Math.max(3, 9)), or to remove ambiguity. A good rule is to leave them out for DSL-like calls (println, assert, build-file directives) and keep them elsewhere.

Comments

GROOVY
// a line comment
/* a block
   comment */
/** Groovydoc: documents the next class or method. */
#!/usr/bin/env groovy   // only valid as the very first line of a file

The #! shebang line is only legal at the top of a file; it lets Unix systems run the script directly.

Identifiers and keywords

Names start with a letter, _ or $ and contain letters, digits, _ or $. Use camelCase for variables and methods and PascalCase for classes. You can also quote a name when you need odd characters, which is common in builders and Spock test names:

GROOVY
def 'a name with spaces'() { }       // inside Spock specifications
def map = ['my key': 1]
println map.'my key'                 // 1

Groovy keywords include def, in, as, trait, var, class, if, else, for, while, switch, try, catch and the usual Java set. it is not a keyword but has special meaning inside closures (see Closures).

Imports and packages

Groovy imports these automatically: java.lang.*, java.util.*, java.io.*, java.net.*, groovy.lang.*, groovy.util.*, java.math.BigInteger and java.math.BigDecimal. Everything else needs an import:

GROOVY
import java.time.LocalDate
import static java.lang.Math.sqrt
import java.util.regex.Pattern as Regex   // alias

println sqrt(16)
println LocalDate.of(2025, 1, 15)

The alias form (as) is handy to avoid name clashes between libraries. Star imports (import java.time.*) also work. A package line at the top places the file's classes into a package, exactly as in Java.

Printing

println is a Groovy method on every object that writes a line to the standard output. print writes without a newline, and printf formats like C or Java:

GROOVY
print 'no newline '
println 'with newline'
printf('%s has %d items%n', 'cart', 3)

The last call prints cart has 3 items. Inside strings you can interpolate values, which you will learn in Strings and GStrings.

The power assert

assert is one of the most useful statements in Groovy. When an assertion fails, Groovy prints the value of every sub-expression:

GROOVY
def x = 10
def y = 4
assert x + y == 14        // passes silently
assert x / y == 2         // fails: x / y is 2.5

The failure output draws the expression and annotates each part with its value, so you see at a glance that x / y was 2.5. This makes assertions an excellent replacement for scattered println debugging, and they are the basis of the Spock tests later in this course.

The Java stand-in below imitates the idea: it checks a condition and reports the values on failure.

Java Java stand-in: an assert that shows its values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Methods

Methods are declared with def or with a return type. The return keyword is optional, parameter types are optional, and parameters can have default values:

GROOVY
def square(n) { n * n }

String describe(String name, int age = 18) {
    "$name is $age"
}

println square(7)               // 49
println describe('Ada')         // Ada is 18
println describe('Linus', 54)   // Linus is 54

A default value makes Groovy generate overloads for you. Methods are public by default and can also be static, private, or protected. Calling a method with the wrong number of arguments gives a MissingMethodException at run time, because Groovy resolves calls dynamically.

Because Groovy returns the value of the last statement, be careful with a method whose last statement is an if without an else: it returns null when the condition is false.

Java Java stand-in: default arguments via overloads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Blocks and indentation

Braces delimit blocks, as in Java. Indentation is for readers only. A pair of braces at the start of a statement can mean a closure rather than a block, which is why Groovy does not allow the Java array initializer {1, 2}.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which package is NOT imported by default in Groovy?

    java.time must be imported explicitly. java.lang, java.util, java.io, java.net, groovy.lang and groovy.util are automatic.
  2. 2. When is a semicolon required in Groovy?

    Newlines end statements. Use ; only when you want two statements on one line.
  3. 3. What does a failing assert x / y == 2 print that makes it so helpful?

    Power assert annotates each part of the expression with its value, so you can see why the condition was false.
  4. 4. What does the following method return? def f(n) { if (n > 0) { 'positive' } } called with f(-1)

    The last statement is an if with no else. When the condition is false nothing is evaluated, so the result is null.

Summary

  • A Groovy file can be a script (statements) or hold classes; scripts get an implicit class and main.
  • Semicolons and many parentheses are optional; end continued lines with an operator.
  • Common packages are imported automatically; use import ... as to alias.
  • println, print and printf write output; assert explains failures.
  • Methods return their last expression and may have default parameter values.

Next: Variables and Typing