Variables and data types in Groovy

In Groovy, variables are used to store data, and data types define the type of data that can be stored in a variable. Here are the data types and variable types in Groovy:

Data Types:

1. Numbers: Groovy supports both integer and floating-point numbers. Integer numbers are defined using the int keyword, while floating-point numbers are defined using the float or double keyword.

2. Strings: Strings are used to represent text data. They are defined using single or double quotes.

3. Booleans: Booleans are used to represent true or false values. They are defined using the boolean keyword.

4. Lists: Lists are used to store a collection of data. They are defined using square brackets ([ ]) and can contain any data type.

5. Maps: Maps are used to store key-value pairs. They are defined using curly braces ({ }) and can contain any data type.

6. Arrays: Arrays are used to store a collection of data of the same type. They are defined using square brackets ([ ]) and can contain any data type.

Variable Types:

1. Local Variables: Local variables are defined within a method or a block of code and can only be accessed within that method or block.

2. Instance Variables: Instance variables are defined within a class and can be accessed by any method within that class.

3. Class Variables: Class variables are defined within a class and can be accessed by all instances of that class.

Here are some examples of defining variables in Groovy:

Defining a variable with an inferred type:

def age = 30

Defining a variable with an explicit type:

int count = 10

Defining a string variable:

String name = 'John'

Defining a boolean variable:

boolean isTrue = true

Defining a list variable:

List fruits = ['apple', 'banana', 'orange']

Defining a map variable:

Map ages = ['John': 30, 'Jane': 25, 'Bob': 40]

Defining an array variable:

int[] numbers = [1, 2, 3, 4, 5]