Variables and Types in Groovy
Learn about variables, data types, and type conversions in Groovy with practical Docker-ready examples
Introduction
Groovy offers one of the most flexible type systems on the JVM. Unlike Java, where every variable requires an explicit type declaration, Groovy lets you choose between dynamic typing with def and explicit static typing — sometimes in the same file. This optional typing is one of Groovy’s defining features.
As a multi-paradigm language that runs on the JVM, Groovy gives you access to all of Java’s types while adding its own conveniences: native syntax for lists and maps, powerful string interpolation with GStrings, and seamless type coercion with the as keyword. You get the rapid prototyping feel of Python or Ruby with the ability to add Java-style type safety when you need it.
In this tutorial, you’ll learn how to declare variables, work with Groovy’s core data types, convert between types, and use constants. All examples are runnable with Docker — no local installation required.
Variable Declaration
Groovy provides two approaches to declaring variables: dynamic typing with def and explicit type declarations using Java types.
Create a file named variables.groovy:
| |
With def, Groovy infers the type at runtime and allows reassignment to different types. With explicit types, you get compile-time checks similar to Java. Notice that Groovy auto-boxes primitives — int becomes Integer, double becomes Double.
Strings and GStrings
Groovy distinguishes between regular Java strings (single quotes) and interpolated GStrings (double quotes). This is an important distinction that doesn’t exist in Java.
Create a file named variables_strings.groovy:
| |
Type Conversions
Groovy provides multiple ways to convert between types, from the as keyword to Java-style casting and constructor-based conversion.
Create a file named variables_types.groovy:
| |
Groovy uses BigDecimal for decimal literals by default rather than double, which avoids the floating-point precision issues common in many languages. The safe navigation operator (?.) and Elvis operator (?:) provide elegant null handling.
Running with Docker
| |
Expected Output
Output from variables.groovy:
Language: Groovy
First appeared: 2003
Pi: 3.14159
Active: true
--- Runtime Types ---
name is String
year is Integer
pi is BigDecimal
active is Boolean
--- Explicit Types ---
greeting: Hello from Groovy (String)
count: 42 (Integer)
ratio: 0.75 (Double)
found: false (Boolean)
--- Dynamic Reassignment ---
value = 100 (Integer)
value = now a string (String)
value = [1, 2, 3] (ArrayList)
Output from variables_strings.groovy:
No interpolation here: ${this is literal}
Type: String
Welcome to Groovy 4.0
Type: GStringImpl
Name: Groovy
Version: 4.0
JVM Language: Yes
Pattern type: Pattern
Matches '555-1234': true
Matches 'hello': false
--- Groovy String Methods ---
Capitalize: Hello groovy world
Contains: true
Reverse: dlrow yvoorg olleh
Words: [hello, groovy, world]
Output from variables_types.groovy:
String '42' as int: 42 (Integer)
Double 3.14159 as int: 3 (Integer)
--- Conversion Methods ---
'100'.toInteger(): 100 (Integer)
'3.14'.toDouble(): 3.14 (Double)
'true'.toBoolean(): true
42.toString(): 42 (String)
--- Big Number Types ---
1.1 is BigDecimal
Large int is Long
Price: 19.99, Tax: 0.08
Total: 21.5892 (BigDecimal)
--- Null Handling ---
null value: null
Safe navigation: null
Elvis operator: default value
--- Constants ---
MAX_SIZE: 100
APP_NAME: GroovyApp
Key Concepts
defvs explicit types: Usedeffor dynamic typing and rapid prototyping; use explicit Java types (String,int,double) when you want compile-time safety or documentation- Auto-boxing: Groovy automatically wraps primitives in their object equivalents —
intbecomesInteger,booleanbecomesBoolean - BigDecimal by default: Decimal literals like
3.14areBigDecimal, notdouble, giving you precise arithmetic out of the box - Single vs double quotes: Single-quoted strings are plain
String; double-quoted strings with${}expressions becomeGString— a Groovy-specific interpolated string type askeyword: Groovy’s idiomatic way to convert between types, cleaner than Java-style casting- Null safety operators: The safe navigation operator (
?.) and Elvis operator (?:) provide concise null handling without verbose if-checks - Dynamic reassignment: Variables declared with
defcan be reassigned to values of completely different types at runtime - Java compatibility: Every Java type works in Groovy — you can mix Groovy’s dynamic features with Java’s static types freely
Running Today
All examples can be run using Docker:
docker pull groovy:4.0-jdk17-alpine
Comments
Loading comments...
Leave a Comment