Groovy Programming Language
The only thing constant in this world is change! In the 1990s, Java shook up the computing world by bringing managed runtime (virtual machines) to mainstream programming. Today, there are many new languages emerging to replace languages that are popular.
Do you know that there are more than two hundred languages that target the Java platform? Languages like Scala, Clojure, Groovy, and JRuby are few important languages that target the Java platform. Of these, of interest to us is Groovy since it is getting extensive attention and gaining steady popularity in the last few years. So explore this article and know more about Groovy.
The user can write Groovy code online and can execute it too quickly to play around with some snippets. Please notice, that the playground currently has some limitations, like System.out.println is not working.
Groovy nearly is a superset of Java, which means most of the Java code is also valid in Groovy code. It just adds a lot of syntactic sugar on top of Java. Let’s see a short example.
This would be valid in Java and Groovy. Except that the user would need at least a class with a main method around it in Java to run. In Groovy user can just place this inside a file, execute it through the console and it will start working. But in Groovy we can shorten this line to:
println “Hello World”
In contrast to Java, user can also use dynamic typing in Groovy. To define a variable, use the keyword “def”. That way Groovy will determine the type of the variable at runtime and the type might even change. For instance, the following snippet is valid for Groovy code:
def x = 42
x = “Hello World”
This script produces the following output:
The variable x changed its type during runtime. The user is still free to define x with a type like int.
Groovy has a String implementation called GString which allows the user to add variables into the String.
def x = “World”
println “Hello, $x”
This would produce the output Hello, World. The content of variable x is inserted into the string. If the user wants to use more difficult statements in the string, then the user need to add curly braces after the dollar sign.
Groovy has some syntactic sugar around regular expressions. The user can define a regular pattern class by placing the ~ in front of a string. Besides the already mentioned single quote and double quotes,there is a third method to define a string, which is primarily meant for regular expressions. The user can define a string inside two slashes /../. The main difference (in contrast to “””) is, that the user does not need to escape a backslash character, which they often need in regular expression patterns.
def pattern = ~/a slash must be escaped \/ but backslash, like in a digit match \d does not/