From the course: Learning Groovy

Groovy and Java - Groovy Tutorial

From the course: Learning Groovy

Groovy and Java

- [Instructor] Why Groovy? That's a question that often comes up with Java developers. In this chapter, I want to give a brief overview on commonalities and improvements between Java and Groovy. The following examples represent a selection of features. There are many more differences between both languages you can explore by yourself. In Java, every source file with the file extension .java has to be compiled to byte code. Only then can it be executed on the JVM. This workflow is a good use case for more complex programs. However, scriptability is somewhat limited. Groovy comes with both modes out of the box. You can compile source code with the file extension .groovy or execute a Groovy program as a script without a main method. Java enforces static typing. When creating a variable, you always have to assign the corresponding type. Groovy provides the option to use the def keyword to determine the type at runtime. This is also called duck typing. Alternatively, a variable can assign a concrete type. You can also tell the Groovy compiler to enforce static typing if needed. Java developers often complain about having to write a lot of boilerplate code. For example, getter and setter methods. While IDEs help with the generation of those methods, it comes at the cost of code readability. In Groovy, getter and setter methods are generated at runtime for a class member. You do not have to write the code for it. Expanding on the topic of boilerplate code, Java requires developers to write constructors and the implementation details of the equals, hashCode, and toString methods. To ease the pain, Groovy provided class-level annotations for generating those methods at compile time, so called AST transformations. Importing any package except java.lang.star is mandatory in Java. In production code, you'll often see a long list of imports. Groovy automatically imports a list of packages commonly used in programs. For example, the collection classes or input/output classes. In Java, the default modifier for classes, methods, and fields is package-private. To expose the functionality, you have to assign the public modifier. Groovy makes everything public by default, which leads to less verbose code. Of course, you can enforce encapsulation as needed. One of my pet peeves of Java is the need to end every statement with a semicolon. In Groovy, semicolons are optional. It is only needed to separate multiple statements on a single line.

Contents