Introduction
In this section, we will cover the basics of variables and data types in Groovy. Understanding these concepts is fundamental to writing effective Groovy scripts and applications.
Variables
Variables are used to store data that can be referenced and manipulated in a program. In Groovy, you can declare variables using the def
keyword or by specifying a type.
Declaring Variables
-
Using
def
keyword:def name = "John Doe" def age = 30 def isStudent = true
-
Specifying a type:
String name = "John Doe" int age = 30 boolean isStudent = true
Variable Naming Rules
- Must start with a letter,
$
, or_
. - Subsequent characters can be letters, digits,
$
, or_
. - Cannot be a reserved keyword (e.g.,
class
,if
,else
).
Example
def city = "New York" int population = 8419000 boolean isCapital = false println "City: $city" println "Population: $population" println "Is Capital: $isCapital"
Data Types
Groovy supports various data types, including primitive types, wrapper types, and complex types.
Primitive Data Types
- byte: 8-bit signed integer
- short: 16-bit signed integer
- int: 32-bit signed integer
- long: 64-bit signed integer
- float: 32-bit floating-point number
- double: 64-bit floating-point number
- char: 16-bit Unicode character
- boolean: true or false
Wrapper Types
Groovy automatically converts between primitive types and their corresponding wrapper types (autoboxing/unboxing).
Primitive Type | Wrapper Type |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Complex Data Types
- String: Represents a sequence of characters.
- List: An ordered collection of elements.
- Map: A collection of key-value pairs.
- Range: Represents a sequence of values.
Example
// Primitive types int a = 10 double b = 20.5 boolean c = true // Wrapper types Integer d = 30 Double e = 40.5 Boolean f = false // Complex types String greeting = "Hello, Groovy!" List<Integer> numbers = [1, 2, 3, 4, 5] Map<String, Integer> ageMap = ["John": 25, "Jane": 30] Range range = 1..5 println "Primitive types: $a, $b, $c" println "Wrapper types: $d, $e, $f" println "Complex types: $greeting, $numbers, $ageMap, $range"
Type Inference
Groovy is a dynamically typed language, meaning you don't always need to specify the type of a variable. The type is inferred at runtime.
Example
def message = "Hello, World!" // Inferred as String def count = 42 // Inferred as Integer def price = 19.99 // Inferred as BigDecimal def isAvailable = true // Inferred as Boolean println "Message: $message" println "Count: $count" println "Price: $price" println "Is Available: $isAvailable"
Practical Exercises
Exercise 1: Variable Declaration
Declare variables for the following:
- Your name
- Your age
- Whether you are a student
Solution:
def name = "Alice" int age = 22 boolean isStudent = true println "Name: $name" println "Age: $age" println "Is Student: $isStudent"
Exercise 2: Data Types
Create variables of different data types and print their values:
- A string representing your favorite quote
- A list of your top 3 favorite numbers
- A map containing the names and ages of 3 friends
Solution:
String favoriteQuote = "To be or not to be, that is the question." List<Integer> favoriteNumbers = [7, 13, 21] Map<String, Integer> friendsAges = ["Bob": 25, "Alice": 28, "Charlie": 30] println "Favorite Quote: $favoriteQuote" println "Favorite Numbers: $favoriteNumbers" println "Friends' Ages: $friendsAges"
Common Mistakes and Tips
-
Uninitialized Variables: Always initialize variables before using them.
def uninitializedVar println uninitializedVar // This will print 'null'
-
Type Mismatch: Ensure the assigned value matches the variable type.
int number = "text" // This will cause a runtime error
-
Using
def
for Type Inference: Usedef
for dynamic typing but be cautious about type inference.def value = 10.5 // Inferred as BigDecimal, not Double
Conclusion
In this section, we covered the basics of variables and data types in Groovy. You learned how to declare variables, the different data types available, and how to use type inference. These concepts are fundamental and will be used throughout your Groovy programming journey. Next, we will explore operators in Groovy, which will allow you to perform various operations on these variables.