Learn/Groovy/2. Values and variables
Lesson 2 of 8
Sign in

Groovy, lesson 2

Values and variables

A variable is a name for a value. You create one by declaring it, and from then on you can read it or give it a new value.

Declaring variables

Groovy gives you two styles. With def (or its synonym var), Groovy works out the type from the value at run time:

def city = "Lyon"
def population = 522_000
def rainy = true

Or you write the type, as in Java, and Groovy makes sure only matching values go in:

String country = "France"
int year = 2026
double price = 4.50

Both are fine. Explicit types document intent and catch mistakes such as putting text into a number variable; def keeps short scripts short. Underscores inside numbers are ignored, so 522_000 is just easier to read.

Basic types

TypeExamplesNotes
int/Integer42, -7whole numbers
long9_000_000_000Lbigger whole numbers
BigDecimal3.14, 0.1the default for decimal literals: exact
double3.14dfast floating point
String"hello", 'hi'text
booleantrue, false
nullnull"no value"

A surprise for Java programmers: a literal like 3.14 is a BigDecimal, an exact decimal number. That is why in Groovy 0.1 + 0.2 == 0.3 is true, which is great for money. Ask any value for its type with .getClass() (or just .class):

Changing a variable

Unlike in purely functional languages, Groovy variables can be reassigned:

Constants

Mark a variable final when it must never change. Assigning to it again is an error. By convention, real constants get UPPER_SNAKE_CASE names:

Naming

Ordinary variables use camelCase: totalPrice, maxSpeed. Names may contain letters, digits, _ and $, but cannot start with a digit. Pick names that say what the value means; daysLeft is better than d.

Strings and numbers together

+ joins strings, and a GString inserts any value. .size() (or .length()) tells you how many characters a string has:

Further reading

  • Groovy syntax: identifiers, strings and numbers
  • Semantics: variable definition

2 exercises to try what you just read.

Exercise 1

Trip budget

A road trip costs fuelPerDay for each of the days, plus a one-off snacks cost. The starter already declares these. Add a variable called total with the full cost and print it in this form:

The program reads no input.

Press Ctrl Enter or Check to test your code.

Exercise 2

Name tag

The starter reads a first name and a last name, one per line. Print the name in "last, first" form, and on the next line the total number of letters in both names.

Sample input:

Sample output:

Press Ctrl Enter or Check to test your code.

println 3.14.class        // class java.math.BigDecimal
println 42.class          // class java.lang.Integer
def score = 0
score = score + 10
score += 5               // shorthand for score = score + 5
println score            // 15
final int MAX_PLAYERS = 4
def apples = 3
println "Apples: " + apples       // Apples: 3
println "Apples: ${apples}"       // the same, more readable
println "Groovy".size()           // 6
Total: 300
Ada
Lovelace
Lovelace, Ada
Letters: 11