Why and When to use Groovy

02 Jan, 2009

I have just started learning Groovy few days back.The first thing that I have asked myself and searched for is ‘Why should i use groovy over java and When I can use Groovy. ?’
I am following the book ‘Programming Groovy’. The things I have understood regarding ‘Why’ part are

Simplicity : Groovy syntax is simple and easy. It saves a lot of code and effort thus increasing the productivity of developer if he had to do the same thing in Java.
in Java
for(int i = 0; i < 3; i++) {
System.out.println("United United..." )

in Groovy

3.times {
println "United United..."

This is just a trivial example but there are lot more things like this.
Groovy’s Dynamicity : This is one reason why coding is made simpler and concepts like polymorphism and
callback patterns are made easy to implement.
class Player {
String name
int age
class Club {
String name
String city
public printNameOfTheFootballingEntity(entity) {
println "the entity with name "+ + " is related to Football"

player = new Player(name:"Giggs", age:35)
club = new Club(name:"ManchesterUnited", city:"Old Trafford")

Consider above code. It prints the following:
the entity with name Giggs is related to Football
the entity with name ManchesterUnited is related to Football

If you observe there is no compile time check for the presence of the property “name” in the entity. While interpreting Groovy checks for this property and if it is not there it throws the Missing Property Exception. Dynamic!! ain’t it?
In Groovy you dont need to end statement with semicolon.
Closures are the piece of code blocks contains some statements. They are like fucntion pointers in C. They are infact objects in groovy and can be passed to functions as arguemts as well. Closures can do the job of callbacks.
For Example
def checkPlayer = {
println it + " is a good Striker"

list = ["Rooney", "Tevez" , "Berbatov" ]

The above code prints the following
Rooney is a good Striker
Tevez is a good Striker
Berbatov is a good Striker

Here ‘it’ represents the each single item in the list that is passed to the Closure ‘checkPlayer’.
The code inside the braces is closure code acting like a callback for all the elements of the set.
The same thing in Java will be a bit more effort to code.
List list = new ArrayList();

for (String player : list) {
private void checkPlayer(String player) {
System.out.println(player + "is a good Striker");

The examples so far shows the ease with which things can be developed with little effort but ultimately have the same result because the groovy code is compiled to bytecode which JVM understands. This can make a developer more productive and it can give more agility.
Groovy accepts almost all Java programs as it can use the Java libraries and it even extends some core Java classes as well.
For example
This prints ‘RooneyTevezBerbatov’. Groovy has added the join() method on the ‘List’ of Java while retaining remaining methods.
All is well. These are some reasons which are good enough for any Java developer to explore Groovy.
Now the big Question arises ‘When can I use Groovy over Java?’ and ‘What sort of applications are targeted?
I am at the moment stuck at this question. Honestly speaking i didn’t get a sufficient answer . I think this ‘When’ question is really important especially if some thing is improved over some other thing and you are comparing both.
Groovy scripts are interpreted at runtime, this might cause some performance overhead, which is not all that bad. You can always compile it to java bytecode to remove that performance penalty.
Other reasons may be revealed to myself after some more exposure, about what kind of applications can be created using Groovy. I will share it my next blog. But any suggestions and thoughts are always welcome!
‘Programming Groovy’ Book

Newest Most Voted
Inline Feedbacks
View all comments
Erik Pragt
Erik Pragt
13 years ago

Nice blog Sunil, though personally I think the question should be: why choose Java over Groovy?
Btw, Groovy scripts are not interpreted at runtime. They are compiled at runtime, and the bytecode is run, not the script itself. The performance overhead you get is not because of this, but because of the invocations in Groovy: everything is done through reflectionm, be it calling a method or accessing properties.
Also, in a ‘normal’ application, you would use a join compiler, which would compile the Groovy code into bytecode, therfore removing the ‘at runtime’ compilation.
Try to write a normal Java application (EJB, Web frontend, etc) in Groovy. I think it will answer your question. I haven’t found a good reason not to use Groovy in my Java applications (and speed is, in our applications, usually totally irrelevant on a language level)

Stephan Schmidt
13 years ago

Basically you’re right. Just to nitpick 🙂
System.out.println(“United United…” )
can be written as just
println(“United United…” )
In Java (Static imports).
List list = new ArrayList();
can be written as
List list = List(“Rooney”, “Tevez”, “Berbatov”)
the static List method is trivial to write with varargs…
(or see Google collections for an implemntation)

Programming is hard –

Maarten Winkels
13 years ago

Nice one, Sunil! Your blog show some very useful features of Groovy with simple examples.
Good question: ‘When should you use Groovy’. Feature wise there is no reason not to use Groovy: Java with all its features is used under the hood and it seems like we’re only adding new features without loosing any, so why not just always use Groovy, as Erik suggests?
I think there are many other factors that make a development environment successful apart from the language used: availability of programmers, infrastructure tooling (build tools, code analysis tools, editors), support from vendors and consultants, etc.
At this point, I don’t know much about how large projects are run that use Groovy, although I have seen that big shops that use Java usually spend a lot of time getting the development environment right. I would guess that to get a working development environment for Groovy, you can build upon the existing tooling for Java (just as the language itself). Maybe somebody with more experience in doing Groovy projects can comment on the when and how question.

Markus Jais
13 years ago

I agree with Eric. I think many Java applications that are currently written can also be written with Groovy. And with the great support in Netbeans 6.5, it’s a real joy.
Groovy code is shorter. And often shorter code is easier to read. Some people find Groovy (or Ruby) less readable than Java, but this is mostly because they have been using Java for 10 years and Groovy for 4 weeks.
If you are proficient in both languages, you will find the shorter Groovy code easier to read most of the time.

James Hughes
James Hughes
13 years ago

One of the big concerns with Groovy is, especially comapred to Java, a distinct lack of tooling. The plugins for Eclipse, NetBeans etc are Passable but certainly not up to the standards of the established Java equivalents. In a big project this is certainly a problem. Escpecially when you need to consider developers experience. Personally I am fine with TextPad but some of my collegues would be lost wihtout the helping hand of eclipse.

Bob Herrmann
13 years ago

Or more simply, “When considering Java or Groovy, choose Groovy.”

13 years ago

Remember, you don’t need to use “text” + var + “text” to concatenate strings! You can Perl/PHP like variable interpolation such as “text $var text” !!! I’m glad Dynamic programming has come to the JVM. Lots of benefit without the loss of performance!

13 years ago

My feeling is that Groovy cannot replace java. There are many situations where duck typing is not so good. But since Groovy is Java, you can type your objects inside a Groovy program. So finally, your aplication becomes a mix of Java and Groovy. But the question of when to use Groovy or not remains unclear (at least to me). Performance is probably an important driver. Tooling (mainly the IDE) is another one; think of refactoring functions provided by IDEs for Java programs: some of them can simply not be implemented for Groovy just because of its “dynamic” nature.

13 years ago

Here there is my experience about when use Groovy. It is possible to embed a groovy console into a java application so you can control your application with groovy scripts you type into the console.
You can into the console fire e method of your java application. It can be useful in development stage to make some tests.
I don’t know if I’m very clear. To sum up in your java code you can launch a console and have access to the parameters and you can call functions.

Jan-Kees van Andel
13 years ago

It might be useful to note that as part of Java 7, the JVM will have MUCH better support for dynamic languages like Groovy.
Think of features like tail calling, invokedynamic and interface injection.
Those features are part of JSR 292.
See for an interface injection article, for a tail calling article and for invokedynamic.
Also, Alex Buckley and Brian Goetz did a talk on the subject at DeVoxx 2008. The slides will be published on somewhere in 2009.

13 years ago

just to complete my precedent post. when I say you can control your java class with the groovy console it’s while your application is running. it’s like with JConsole where you can control your JMX Beans. But with Groovy it’s more powerful.

robert zaleski
robert zaleski
13 years ago

To me dynamic/scripting languages break down in projects of a large size. I think of it being like writting C with tons of pointers. There is a lot of power (with dynamically adding methods and variables) but this is the very thing that makes it hard to scale well. You get easier testing, but you HAVE to test everywhere, if nothing else to make sure your spelling is correct. I’ve worked on two large systems in PERL and JavaScript and both have gotten unruly when they hit a certain size.
For quick or very isolated chunks, I love dynamic languages, especially Perl. But for anything that may grow into something large I would hesitate.
Just my two cents.

13 years ago

Hi there,
I often thought about the same question, too. First of all I am not the biggest fan of all those dynamic languages as I prefer static typing. For me personal, it is very important when I read code to allways know what the type of an particular object is. Others will say “Hey, Dynamic languages are easliy readable by any human”. That´s true. But when it comes to more technical details this doesn´t help you anymore. You have to dive into a debug session .. I think groovy as an dynamic language is perfect for building very isolated and autarc components where only one developer makes it all. But I could not imagine a big team building an enterprise project explicitly using groovy. This could work if you have a big catalogue of coding and naming conventions to give some guidelines. But I doubt that really works in reality.
I think this is not a groovy problem but a problem of nearly all dynamic languages.
My 2 cents ..

Josh Brown
13 years ago

One thing I really like about Groovy is that it removes the need for String concatenation, so in your above example, you could’ve done this:
def checkPlayer = {
println “$it is a good Striker”
To put a variable’s value in a String, just use the dollar sign syntax as shown above. You can also use it when calling methods on objects, like so:
public printNameOfTheFootballingEntity(entity) {
println “the entity with name ${} is related to Football”
No plus signs necessary!

11 years ago

Language will last only if it is of any practical use. The question you asked is really valid but answers are not. Those can’t be the reason for using Groovy. Someone (from Groovy community) has to give few practical usage (with good documentation) then only people will start using it for commercial purpose (not only as hobby). Once that process is triggered, automatically new people will start giving more creative inputs, igniting the whole process.
Right now, I only have opinion that Groovy can be lot more helpful (whether it can replace Java or not is not at all important) but how I don’t know. I’m starting some research on using “Groovy with Window”, will let you know the result if it turn out to be practical solution [more detail – want to execute vb macros through Groovy( or java) as no proper solution for excel in java is available. POI disappointed us!!!].

11 years ago

Jan-Kees van Andel, thanks for those links (Java 7).

Sandeep Sangole
Sandeep Sangole
10 years ago

I am using groovy in my project.But I dont see much benefit except its dynamic and saves few lines of code. I think if groovy helps more on performance ,then it would be good idea to go for groovy.

Denisha Stjohns
10 years ago

I was just looking for this information for a while. After 6 hours of continuous Googleing, finally I got it in your website. I wonder what’s the lack of Google strategy that don’t rank this kind of informative websites in top of the list. Normally the top websites are full of garbage.

Elangovan ARUMUGAM
Elangovan ARUMUGAM
9 years ago

Thanks a lot Erik Pragt, Maarten Winkels and Markus Jais
Got very good clarification about Groovy’s Compilation and Run the script.
And many thanks to Sunil Prakash Inteti posted this blog.
As discussed by Markus Jais, Now only we are started to work on Groovy, so we feel Java is providing a better readability.
I am new to Groovy-2.1. Started to develop groovy applications thro Eclipse 4.2 (Juno)
Development Builds
Eclipse level : 4.2 (Juno)
Development update site:
Please read this to do groovy setup:
A. Environment Setup
1. Download JDK-1.6 (jdk1.6.0_23) and Install in the following location
C:\Program Files\Java\jdk1.6.0_23
2. Download Tomcat 6.0 (apache-tomcat-6.0.24)
Unzip it in the following location
C:\Program Files\apache-tomcat-6.0.24
3. Download Eclipse 4.2 (eclipse-jee-juno-RC3-win32 – Juno)
go to Help menu -> Install New Software -> Click Add button
Name: Groovy Dev Plugins
4. Download MySQL 5.5 Server and install it at C:\Program Files\MySQL\
5. Set Environment variables
Select Computer icon-> properties -> Advanced system settings -> Environemnt Variables
User variables ->
Variable name : JAVA_HOME
Variable value : C:\Program Files\Java\jdk1.6.0_23
Variable name : TOMCAT_HOME
Variable value : C:\apache-tomcat-6.0.24
Variable name : GROOVY_HOME
Variable value : C:\groovy-binary-2.0.1\groovy-2.0.1
Variable name : GRAILS_HOME
Variable value : C:\grails-2.1.0\grails-2.1.0
System variables ->
Edit Path
Variable name : Path
Variable value : ;%JAVA_HOME%/bin;%TOMCAT_HOME%/bin;%GROOVY_HOME%/bin;%GRAILS_HOME%/bin;
6. Create a workpace folder in the following location
Copy CoEGroovy folder from Project to groovy_on_grails_workspace
Then open Eclipse-4.2 Juno IDE,
It will ask to open this IDE in a workspace, please refer “C:\groovy_on_grails_workspace”
7. Load Existing Project from Workspace
File -> Import -> General -> Existing Projects into Workspace click Next
Select root directory: click on Browse button, which should be points in to C:\groovy_on_grails_workspace\CoEGroovy
Then click Finish
8. To avoild compilation issue
Select CoEGroovy Project -> right click -> Properties -> Java Build Path -> click on Add JARs…
CoEGroovy -> lib
add releavant jars, Then click Ok, Ok …

6 years ago

Groovy makes the code very simple and helps quick development. But for an enterprise application I will not use it because you’ll discover many conding errors at runtime while you can early see them with Java. When you use a wrong field in your code, there is an impact from front to back-end and companies will not accept that.
– Quick but not safe as Java
– Refactoring huge applications is easier with Java… can you do that with Groovy ?
– Groovy is nice but not robut in my opinion
For me Groovy is a nice to have

Jesse Boyd
Jesse Boyd
4 years ago

So let me get this straight groovy removes type checking so that I can get many more runtime errors and missing property exceptions? I would rather write complete compile time checked code any day. One of the beautiful features to me is the descriptive syntax of Java, the semi colons and clearly defined method arguments make reading/debugging code easier. Code maintenance is one of the biggest expenses in software development, so saving a little time writing code might not really be any savings at all and even a deficit over time. This seems like JavaScript(JS) forcing itself on Java and again I prefer Java over JS because of it’s strict typing and actually we are seeing JS moving towards typing as they see how sloppy the JS code can become. I can’t say learning a whole new set of syntax for groovy looks worth it. And I really can’t see why a well architect-ed program would need to be dynamic at runtime?, especially is you use SOLID and OO design patterns! Thanks for the article.

4 years ago

Thanks Jesse Boyd. I think exactly the same.

2 years ago

Well, I have used groovy in a project with java for testing purpose for a year now. One thing I can confirm is developers are not interested in groovy. Reason is it is just saving us few line of code but making things complex at large level.
People are habitual to use java and with defined patterns and lot of material on net, it is easy to find solution or standard of doing something which is missing for any dynamic language.
It is saving a few lines (which can be automated by IDEs) but adding complexity for developers, increasing development time,
Trends: per trends, groovy or many other languages are nowhere in competition.
I personally don’t see any reason to use these languages as replacement of java, but may be very specific use case that was initial target of it.

Explore related posts