Groovy and Grails Recipes
Groovy and Grails Recipes
CHAPTER 2 From Java to Groovy (S. 17-18)
If you are reading this book, you probably have some experience working with Java. As I explained in the introduction, this book assumes an intermediate- level knowledge of Java. This is because I have noticed that most people learning Groovy have some Java background, and-impatient with the shortcomings and limitations of Java-have decided to give Groovy a try.
They couldn't be more right! This chapter focuses mainly on explaining the similarities and differences between Java and Groovy and how to integrate Groovy with Java. Thanks to the similarity between Groovy's syntax and Java's, the transition from Java to Groovy is a smooth one with an almost flat learning curve. As a matter of fact, Java developers can learn and start programming with Groovy in less than a day. It doesn't get much easier than that!
2-1. What Are the Similarities Between Java and Groovy?
Most of Groovy's code should look instantly familiar to Java developers. As a matter of fact, Java developers can start up the Groovy console and start playing with Groovy before even reading a word about Groovy's syntax. Almost all Java code can be compiled as is with no errors by using the command. Both Java and Groovy are compiled languages. They compile to the same intermediate binary format (bytecode), which runs on the same virtual machine (JVM). As mentioned in Chapter 1, this model guarantees perfect interoperability between Groovy code and Java code and enables Java developers to use Groovy with all of their favorite Java- based frameworks and libraries.
Almost all of Java's syntax is part of Groovy, therefore, Groovy can be considered a near superset of Java. The only Java elements that Groovy doesn't support at the moment are nested and anonymous inner classes. Groovy replaces them with closures, which are much more powerful. However, future versions of Groovy might add support to Java's inner and anonymous classes, thus completing the superset. The decision to make Groovy support almost all of Java's syntax was a deliberate one on the part of the Groovy developers.
They wanted to provide seamless integration with Java, and to make the transition from Java to Groovy as smooth and easy as possible. Even though Groovy's syntax can be considered a near superset of Java, you should be aware of the few semantic differences. For example, I showed in Chapter 1 that Groovy performs floating- point division by default when both operands are integers. In contrast, Java performs integer division. Another example is the operator, which in Groovy, unlike Java, denotes equality rather than identity.