Groovy script for Hello World

We have discussed what Groovy is and some of its important features. Let us create a Hello World program and feel the magic with Groovy. Here we are assuming that Groovy is installed on the system, GROOVY_HOME is pointing to the installation directory and <GROOVY_HOME>/bin has been added to the PATH environment variable:

file: GroovyTest.groovy
  println "Hello Groovy"

And that's all. Yes, for a simple Groovy program, you don't need to declare any packaging, any main class, or any semicolons, only a simple println statement would create your first Groovy program.

To execute the program, use the following command:

$ groovy GroovyTest.groovy
  Hello Groovy

The groovy command is used to execute the Groovy script. The beauty of the Groovy script is that it can execute any file, not only files with the .groovy extension. Even you can write the preceding println statement in the Test.text file and use the groovy command to execute the file. File extension doesn't matter in groovy, but to make the file structures more readable, it is recommended to use .groovy extensions for Groovy files.

There is another way of executing Groovy files. You can compile Groovy files, generate class files like Java, and then execute the class files. Perform the following steps:

  1. To compile and generate the class file, use the following command:
    $ groovyc GroovyTest.groovy
    
  2. To run the class file generated, you need to execute the following command on Windows. If executing on Linux/Unix environment use $GROOVY_HOME:
    $ java -cp %GROOVY_HOME%/embeddable/groovy-all-2.3.1.jar;. GroovyTest
    

Executing a Groovy compiled file is same as executing the Java file. Developer needs to add groovy-all-<version>.jar in its classpath. You also need to make sure that the directory in which your compiled classes are present, it should be in the classpath. In the preceding example, we have added "." as the current directory to the classpath to find the GroovyTest.class file.

It doesn't matter which way you execute the Groovy scripts. In both the cases, Groovy scripts execute inside JVM only. Both the methods compile the Groovy scripts into bytecode. The groovy <filename> stores the classes into memory in a direct way, whereas compiling the script using the groovyc command creates a class file and stores it on disk, which you can later execute using Java command.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.225