Apache Groovy is an Object-oriented programming language used for Java platform. This dynamic language has many features which are similar to Python, Ruby, Smalltalk, and Pero. It can be used as a scripting language for the Java platform.
It is almost like a super version of Java which offers Java's enterprise capabilities. It also offers many productivity features like DSL support, closures, and dynamic typing. Unlike some other languages, it is designed as a companion, not a replacement for Java.
Groovy source code gets compiled in Java Bytecode so it can run on any platform if JRE is installed on that operating system. Groovy also performs a lot of tasks behind the scene that makes it more agile and dynamic.
In this course, you will learn-
Here, are major reasons why you should use Groovy-
Step 1) Ensure you have Java installed. https://www.guru99.com/install-java.html
Step 2) Go to http://groovy-lang.org/download.html and click installer.
Note: You can also install Groovy using the Zip file or as an Eclipse IDE. In this tutorial, we will stick to Windows Installer
Step 3) Launch the downloaded installer. Select language and click OK
Step 4) Launch. In welcome screen, click NEXT
Step 5) Agree with the license terms
Step 6) Select components you want to install and click next
Step 7) Select Installation Directory and click Next
Step 8) Choose Start Menu Folder and Click Next
Step 9) Once install is done, let the paths default and click next
Step 10) Click Next.
Step 11) In start Menu search for Groovy Console
Consider we want to print a simple string "Hello World" in Java. The code to achieve this would be
public class Demo { public static void main(String args[]) { System.out.println("Hello World"); } }
The above code is valid in both Java and Groovy as Groovy is a superset of Java. But the advantage with Groovy is that we can do we away with class creation, public method creation, etc and achieve the same output with a single line code as follows:
println "Hello World."
There is no need for semicolons
There is no need for parenthesis
System.out.println is reduced to println
In Java, static binding is compulsory. Meaning the type of a variable has to be declared in advance.
public class Demo { public static void main(String args[]) { int x = 104; System.out.println(x); //x = "Guru99"; } }
In the above example type of variable (integer) is declared in advance using the keyword "int". If you were to declare a floating point number you use the keyword float.
If you try to assign a String value to an int (uncomment line #5), you will get the following error
Demo.java:5: error: incompatible types: String cannot be converted to int x = "Guru99";
In contrast, Groovy supports Dynamic Typing. Variables are defined using the keyword "def," and the type of a variable does not need to be declared in advance. The compiler figures out the variable type at runtime and you can even the variable type.
Consider the following groovy example,
def x = 104 println x.getClass() x = "Guru99" println x.getClass()
Output
class java.lang.Integer class java.lang.String
In Groovy, you can create multiline strings. Just ensure that you enclosed the String in triple quotes.
def x = """Groovy at Guru99""" println x
Output
Groovy at Guru99
Note: You can still variable types like byte, short, int, long, etc with Groovy. But you cannot dynamically change the variable type as you have explicitly declared it.
Consider the following code:
int x = 104 println x x = "Guru99"
It gives the following error
104 Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Guru99' with class 'java.lang.String' to class 'int' org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Guru99' with class 'java.lang.String' to class 'int' at jdoodle.run(jdoodle.groovy:3) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) Command exited with non-zero status 1
An operator is a symbol which tells the compiler to do certain mathematical or logical manipulations.
Groovy has the following five types of operators –
In Java, you would define a loop as follows
public class Demo { public static void main(String args[]) { for (int x = 0; x <= 5; x++) { System.out.println(x); } } }
Output
0 1 2 3 4 5
You can achieve the same output in Groovy using upto keywords
0.upto(4) {println "$it"}
You get the same output as above. $it is a closure that gives the value of the current loop.
Consider the following code
2.upto(4) {println "$it"}
It gives an output
2 3 4
You can also use the "times" keyword to get the same output
5.times{println "$it"}
Consider, you want to print 0,2,4,6 with for loop in Java
public class Demo { public static void main(String args[]) { for (int x = 0; x <= 5; x=x+2) { System.out.println(x); } } }
Output:
0 2 4 6
You can use the step method for the same
0.step(7,2){println "$it"}
Statements | Deception |
if Statement | As in Java, the if statement is executed if the condition is true. |
if/else Statement | In if/else statement at first a condition is evaluated in the if statement. If the condition is true then executes the statements after that. It stops before the else condition and exits out of the loop. However, If the condition is false then executes the statements in the else statement block. Then it exits the loop. |
Nested If Statement | It is used when there is a requirement to have multiple if statements. |
Switch Statement | The nested if-else statement could become unreadable when you have multiple conditions. To make code more readable switch statement is used. |
Nested Switch Statement | In Groovy is also possible to use nested switch statements. |
List structure allows you to store a collection of data Items. In a Groovy programming language, the List holds a sequence of object references. It also shows a position in the sequence. A List literal is presented as a series of objects separated by commas and enclosed in square brackets.
Example of Grrovy list:
A list of Strings- ['Angular', 'Nodejs,]
A list of object references - ['Groovy', 2,4 2.6]
A list of integer values - [16, 17, 18, 19]
An empty list- [ ]
Following are list methods available in Groovy:
Methods |
Description |
add() |
Allows you to append the new value to the end of this List. |
contains() |
Returns true if this List contains a certain value. |
get() |
Returns the element at the definite position |
isEmpty() |
Returns true value if List contains no elements |
minus() |
This command allows you to create a new List composed of the elements of the original excluding those which are specified in the collection. |
plus() |
Allows you to create a new List composed of the elements of the original together along with mentioned in the collection. |
pop() |
Removes the last item from the List |
remove() |
Removes the element at the specific position |
reverse() |
Create a new List which reverses the elements of the original List |
size() |
Allow finding some elements |
sort() |
Returns a sorted copy |
Consider the following example
def y = ["Guru99", "is", "Best", "for", "Groovy"] println y y.add("Learning") println(y.contains("is")) println(y.get(2)) println(y.pop())
Output
[Guru99, is, Best, for, Groovy] true Best Learning
A Map Groovy is a collection of Key Value Pairs
Examples of Groovy maps:
Here, is a list of map methods available in Groovy.
Methods |
Description |
containsKey() |
Check that map contains this key or not? |
get() |
This command looks up the key in this Map and returns the corresponding value. If you don't find any entry in this Map, then it will return null. |
keySet() |
Allows to find a set of the keys in this Map |
put() |
Associates the specified value with the given key in this Map. If the Map earlier contained a mapping for this key. Then the old value will be replaced by the specified value. |
size() |
Returns the number of key-value mappings. |
values() |
This command returns a collection view of the values. |
Groovy Example:
def y = [fName:'Jen', lName:'Cruise', sex:'F'] print y.get("fName")
Output
Jen
A groovy closure is a piece of code wrapped as an object. It acts as a method or a function.
Example of simple closure
def myClosure = { println "My First Closure" } myClosure()
Output:
My First Closure
A closure can accept parameters. The list of identifies is comma separated with
an arrow (->) marking the end of the parameter list.
def myClosure = { a,b,c-> y = a+b+c println y } myClosure(1,2,3)
Output
6
A closure can return a value.
def myClosure = { a,b,c-> return (a+b+c) } println(myClosure(1,2,3))
Output
6
There are many built-in closures like "It", "identity", etc. Closures can take other closure as parameters.
Groovy |
Java |
In Groovy, default access specifier is public. It means a method without any specified access modifier is public and accessible outside of class and package boundaries.
|
In Java, the default access modifier is a package, i.e., if you don't specify access modifier for fields, methods or class it becomes package-private,
|
Getters and setters are automatically generated for class members.
|
Java, you need to define getters and setters method for fields
|
Groovy allows variable substitution using double quotation marks with strings. |
Java does not support variable substitution. |
Typing information is optional. |
Typing information is mandatory in Java. |
Groovy it's not required to end with a semicolon. |
In Java, every statement ends with a semicolon. |
Groovy is automatically a wrapping class called Script for every program |
In Java, you need the main method to make a class executable.
|
Myth |
Reality |
We can use Groovy just for scripting. |
It can be used for scripting. However, you can perform many other tasks apart from it. |
Groovy is all about closures. "It's just functional programming language." |
Groovy adopts from functional programming languages like Lisp or Closure. |
Groovy is an ideal choice if you want do TDD |
This statement is true. However, it is certainly not the only reason to use Groovy. |
You can use Groovy only if you want to use Grails. |
Grails is a powerful web development framework. But Groovy offers more than that. |
We will discuss 3 important tools
1. groovysh: Executes code interactively.
2. groovyConsole: GUI for interactive code execution
3. groovy: Executes groovy scripts. You can use it like Perl, Python, etc.
Groovysh
Groovy console
Groovy
It is the processor which executes Groovy programs and scripts. U
It can be used to test simple Groovy expressions.