Variables are placeholders.
What do I mean by this?
If you remember in math if you do something like x = 1
and then you write something like 1 + x
, that means you can put instead of x
, 1
, so we can write: 1 + 1
.
The same principle is applied in Groovy.
Now, in Groovy to use a variable we need to declare it.
Declaring Variables:
The classic and most used way to declare a variable is like so:
def variable_name = SomeValueHere
- here we use the key word
def
, which stands for definition. variable_name
, this is just a name you give to a variable, it is also known as the variable identifier.
1 ) There are some rules that should be respected when giving variable names.
A variable name can not start with a number, like def 6x = 1
If you do that, an error like below it will be displayed by the console
Error: Error parsing script
Error parsing expression: startup failed: Script2.groovy: 4: unexpected token: def
2 ) Variable names can start with a letter, a dollar sign and also an underscore:
Examples of valid variable names:
def name
def _item
def with_underscore
def $dollarStart
Examples of Invalid Variable Names:
def 3tier
def x+y
def x#y
As a side note I like to name my variables like var_SomeName
, I find it much easier to read through the code later on and spot where I have used variables.
3 ) the sign =
- this is called the assignment operator and what it does is to assign a value to the variable.
So if you do def x = 10
, it is saying put the integer 10 into the variable named x
Now there are some other ways we can define variables, that approach more of the static style of programming languages like JAVA.
For example we can do something like:
Integer x = 10;
And what this means is that we are specifically defining the type of data that we want to keep in our variable.
In this case we are saying variable name x
will hold only Integer numbers.
Before, when we used def
key word, to define a variable, that allows the Groovy engine to determine at run-time the type of the variable base on what value it holds.
This is called dynamic typing.
How and what kind of data can be put into a variable?
Well, anything can be stored into a variable: text, a single character, numbers or Boolean values.
Let's see some examples:
def var_A = "Some Text"
def var_B = "c"
def var_C = 11
def var_D = true // true is a Boolean value
Notice 1 thing here: text (String) is written encapsulated in " "
or ' '
So if We write "1"
and 1
, the two are not the same, first time we have a string that happens to be 1 and the second time we have the number 1 that we can use in mathematical operations.