Introduction to Groovy:
Groovy is a powerful, dynamic programming language that runs on the Java Virtual Machine (JVM). It combines the best features of Java with added simplicity and productivity. Groovy is widely used in various domains, including scripting, web development, build automation, and more. This tutorial aims to provide a step-by-step introduction to Groovy for beginners.
Installing Groovy:
To start using Groovy, you need to have Java installed on your system. Follow these steps to install Groovy:
- Download the latest Groovy binary distribution from the official website (https://groovy-lang.org/download.html).
- Extract the downloaded archive to a preferred location on your system.
- Set the
GROOVY_HOME
environment variable to the directory where you extracted Groovy. - Add the Groovy bin directory to your system's
PATH
variable.
Hello World in Groovy:
Let's begin with a simple "Hello World" example in Groovy.
groovy// hello_world.groovy
class HelloWorld {
static void main(String[] args) {
println "Hello, World!"
}
}
Explanation:
- In Groovy, a class can be defined using the
class
keyword, just like in Java. - The
static void main(String[] args)
method is the entry point of the Groovy program. - The
println
statement is used to output "Hello, World!" to the console.
Variables and Data Types:
Groovy supports various data types similar to Java, including int
, double
, String
, boolean
, etc. Variables in Groovy do not require explicit type declarations.
groovydef name = "John"
def age = 30
def salary = 50000.50
def isEmployed = true
Conditional Statements:
Groovy supports familiar conditional statements like if
, else if
, and else
.
groovydef num = 10
if (num > 0) {
println "Positive number."
} else if (num < 0) {
println "Negative number."
} else {
println "Zero."
}
Loops:
Groovy provides loop constructs like for
, while
, and each
for iteration.
groovy// For loop
for (int i = 1; i <= 5; i++) {
println "Iteration $i"
}
// While loop
def count = 0
while (count < 5) {
println "Count: $count"
count++
}
// Each loop for lists
def fruits = ["Apple", "Banana", "Orange"]
fruits.each { fruit ->
println "Fruit: $fruit"
}
Functions in Groovy:
Functions in Groovy are defined using the def
keyword.
groovydef addNumbers(int a, int b) {
return a + b
}
def result = addNumbers(5, 7)
println "Result: $result"
Classes and Objects:
Groovy supports object-oriented programming with classes and objects.
class Person {
def name
def age
def introduce() {
println "Hi, I am $name and I am $age years old."
}
}
def person1 = new Person(name: "Alice", age: 25)
person1.introduce()
Conclusion:
Congratulations! You've completed the basic introduction to Groovy. This tutorial covered fundamental concepts such as variables, conditional statements, loops, functions, classes, and objects in Groovy. With this foundation, you can explore more advanced topics and leverage the power of Groovy for your projects. Happy coding!
0 Comments