May 14, 2021 Groovy
Variables in Groovy can be defined in two ways - using the local syntax of the data type, or using the def keyword. ed. his is what Groovy parsers need.
Groovy has the following basic types of variables, as described in the previous chapter -
Byte - This is used to represent byte values. F or example, 2.
short - used to represent a short number. F or example, 10.
int - This is used to represent integers. F or example, 1234.
long - This is used to represent a long number. F or example, 10000090.
float - used to represent 32-bit floats. F or example, 12.34.
double - This is used to represent a 64-bit float. F or example, 12.3456565.
char - This defines a single character text. F or example, 'a'.
Boolean - This represents a Boolean value that can be true or false.
String - This is text expressed as a string. F or example, Hello World.
Groovy also allows other types of variables, such as arrays, structures, and classes, which we'll see in later chapters.
Variable declarations tell the compiler where and how much to create storage for variables.
Here is an example of a variable declaration -
class Example { static void main(String[] args) { // x is defined as a variable String x = "Hello"; // The value of the variable is printed to the console println(x); } }
When we run the program above, we get the following results -
Hello
The name of a variable can consist of letters, numbers, and underscore characters. I t must begin with a letter or underscore. C apital and lowercase letters are different because Groovy, like Java, is a case-sensitive programming language.
class Example { static void main(String[] args) { // Defining a variable in lowercase int x = 5; // Defining a variable in uppercase int X = 6; // Defining a variable with the underscore in it's name def _Name = "Joe"; println(x); println(X); println(_Name); } }
When we run the program above, we get the following results -
5 6 Joe
We can see that x and X are two different variables because case sensitive, and in the third case, we can see _Name the following dash.
You can use the println function to print the current value of the variable. T he following example shows how this can be achieved.
class Example { static void main(String[] args) { //Initializing 2 variables int x = 5; int X = 6; //Printing the value of the variables to the console println("The value of x is " + x + "The value of X is " + X); } }
When we run the program above, we get the following results -
The value of x is 5 The value of X is 6