CodeToLive

Groovy Syntax

Groovy's syntax is designed to be familiar to Java developers while being more concise and expressive. Here are the key syntax features that make Groovy powerful and productive.

Basic Syntax Differences

// Java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

// Groovy equivalent
println "Hello, World!"

Optional Elements

  • Semicolons: Optional at the end of statements
  • Parentheses: Optional for top-level expressions
  • Return keyword: Optional (last expression is returned)
  • Public modifier: Default for classes and methods

Strings

Groovy supports multiple string types:

// Single-quoted string (plain java.lang.String)
def name = 'Groovy'

// Double-quoted string (groovy.lang.GString if it contains interpolation)
def greeting = "Hello, ${name}!"

// Triple-quoted string (multi-line)
def multiLine = '''
    This is a multi-line
    string in Groovy
'''

Collections

Simplified syntax for lists and maps:

// List
def numbers = [1, 2, 3, 4, 5]
numbers << 6  // Add element

// Map
def person = [name: 'John', age: 30]
person.city = 'New York'  // Add key-value pair

Operators

Groovy adds several useful operators:

Operator Description Example
?. Safe navigation person?.address?.city
*. Spread operator people*.name
?: Elvis operator name ?: 'Default'
== Equals (uses equals() method) str1 == str2
← Back to Tutorials