Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Groovy Basics: Syntax and Semantics

3. Groovy Basics: Syntax and Semantics

In this section, we'll explore the fundamental building blocks of the Groovy programming language, including its syntax and semantics. Groovy shares many similarities with Java but introduces several features that make it more concise and expressive.

1. Writing Your First Groovy Script:

  • Start by creating a new text file with a '.groovy'extension (e.g., 'HelloWorld.groovy').
  • In your script, you can write a simple "Hello, World!" program:
println("Hello, World!")

  • Save the file and open a terminal or command prompt.
  • Run your Groovy script using the 'groovy' command:
groovy HelloWorld.groovy
 
  • You should see the "Hello, World!" message printed to the console.

2. Comments:

Groovy supports single-line comments using  '//'and multi-line comments using '/* ... */' just like Java.

// This is a single-line comment
/* This is
   a multi-line
   comment */
 

3. Variables and Data Types:

  • Groovy is dynamically typed, so you don't need to declare variable types explicitly.
  • Variables are defined using the 'def' keyword
def age = 30
def name = "Alice"

  • Groovy supports common data types like integers, strings, lists, maps, and more.

4. Strings:

You can define strings using single or double quotes.

def singleQuoted = 'This is a single-quoted string.'
def doubleQuoted = "This is a double-quoted string with interpolation. My name is ${name}."
 

String interpolation allows you to embed variables and expressions within double-quoted strings.

5. Basic Operators:

  • Groovy supports common arithmetic operators ('+', '-' , '*' , '/',  '%') and comparison operators ('==', '!=', '<', '>', '<=', '>=').
  • You can perform operations on variables and literals as expected.
def result = age * 2
def isEqual = age == 30
 

6. Control Structures:

Groovy supports 'if-else'statements and 'switch' expressions similar to Java.

'if-else' example:
if (age < 18) {
    println("You are a minor.")
} else {
    println("You are an adult.")
}
 
'switch' example:
def dayOfWeek = "Tuesday"
switch (dayOfWeek) {
    case "Monday":
        println("It's the start of the week.")
        break
    case "Tuesday", "Wednesday":
        println("It's the middle of the week.")
        break
    default:
        println("It's the end of the week.")
}
 

7. Loops:

Groovy supports 'for', 'while', and 'each'loops for iterating over collections and ranges.

'for' loop example:
for (i in 1..5) {
    println("Iteration ${i}")
}

 

'each' loop example (for collections):
def numbers = [1, 2, 3, 4, 5]
numbers.each { num ->
    println("Number: ${num}")
}
 

8. Functions and Methods:

  • You can define functions/methods using the 'def' keyword.
  • Groovy also supports optional parentheses for function calls.
def greet(name) {
    println("Hello, ${name}!")
}
greet("Bob")
greet "Alice"  // Parentheses are optional
 

9. Lists and Maps:

Groovy provides convenient syntax for defining lists and maps.

def colors = ['red', 'green', 'blue']
def person = [name: 'John', age: 25]
 

Lists are ordered collections, and maps are key-value pairs.

10. Exception Handling:

Groovy supports 'try-catch-finally' blocks for handling exceptions, similar to Java.

try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Handle the exception
} finally {
    // Optional cleanup code
}
 

These are the foundational aspects of Groovy's syntax and semantics. By understanding these basics, you'll be well-equipped to start writing Groovy code and exploring its more advanced features and capabilities.