In this section, we will write our first Groovy script. This will help you get familiar with the basic syntax and structure of a Groovy program. By the end of this section, you should be able to write and run a simple Groovy script.
Objectives
- Understand the structure of a Groovy script.
- Write and execute a basic Groovy script.
- Learn how to print output to the console.
Writing Your First Groovy Script
Step 1: Create a New File
- Open your preferred text editor or Integrated Development Environment (IDE).
- Create a new file and name it
FirstGroovyScript.groovy
.
Step 2: Write the Script
Let's start with a simple script that prints "Hello, Groovy!" to the console.
// FirstGroovyScript.groovy // This is a single-line comment /* This is a multi-line comment */ // The following line prints "Hello, Groovy!" to the console println 'Hello, Groovy!'
Explanation
- Comments:
- Single-line comments start with
//
. - Multi-line comments are enclosed between
/*
and*/
.
- Single-line comments start with
- Printing to Console:
- The
println
function is used to print text to the console. In this case, it printsHello, Groovy!
.
- The
Step 3: Run the Script
To run the script, follow these steps:
- Open your terminal or command prompt.
- Navigate to the directory where you saved
FirstGroovyScript.groovy
. - Run the script using the
groovy
command:groovy FirstGroovyScript.groovy
Expected Output
When you run the script, you should see the following output in the console:
Practical Exercise
Exercise 1: Modify the Script
Modify the script to print your name instead of "Hello, Groovy!".
Solution
// FirstGroovyScript.groovy // This is a single-line comment /* This is a multi-line comment */ // The following line prints "Hello, [Your Name]!" to the console println 'Hello, [Your Name]!'
Replace [Your Name]
with your actual name.
Exercise 2: Add More Print Statements
Add additional println
statements to print the following:
- Your favorite programming language.
- Your favorite hobby.
Solution
// FirstGroovyScript.groovy // This is a single-line comment /* This is a multi-line comment */ // The following lines print various information to the console println 'Hello, [Your Name]!' println 'My favorite programming language is Groovy.' println 'My favorite hobby is [Your Hobby].'
Replace [Your Name]
and [Your Hobby]
with your actual name and hobby.
Common Mistakes and Tips
- Syntax Errors: Ensure that you use the correct syntax for comments and print statements.
- File Extension: Make sure your file has the
.groovy
extension. - Running the Script: Ensure you are in the correct directory when running the script from the terminal.
Summary
In this section, you learned how to write and run a basic Groovy script. You now know how to:
- Create a new Groovy file.
- Write comments in Groovy.
- Use the
println
function to print output to the console.
Next, we will dive deeper into Groovy syntax and language features, starting with variables and data types.