Hello World (Groovy)

From LiteratePrograms
Jump to: navigation, search
Other implementations: Alice ML | Amiga E | AspectJ | Assembly Intel x86 Linux | Assembly Intel x86 NetBSD | AWK | bash | BASIC | Batch files | C | C, Cairo | C, Xlib | Candle | C++ | C# | Dylan | E | Forth | FORTRAN | Fortress | Go | Groovy | IBM PC bootstrap | Inform 7 | JavaScript | LaTeX | Logo | LOLCODE | Lua | MATLAB | OCaml/F Sharp | occam | Oz | Perl | PHP | PIR | PLI | Prolog | Python | Rexx | Ruby | Scheme | sh | SQL | Standard ML | Tcl | Tcl Tk | Visual Basic

This program is under development.
Please help to debug it. When debugging
is complete, remove the {{develop}} tag.

Groovy is a Java-like scripting language that borrows many ideas from Ruby and Python. It is designed to work well with the Java programming language and runs on the Java Virtual Machine. Its main strengths are its initial similarity to Java and its access to the large collection of facilities in the Java APIs. The language reached its 1.0 release in December 2007 and this article is a minor celebration of that fact.

To run this example, you will need to install a Java development kit and Groovy to run these examples. Instructions for this is beyond the scope of this article but see Installation Instructions at the Groovy Language Home Page.

This is a simple Groovy program that prints a string to the console, then prints the integers 1 through 10 using a simple for loop.

print greeting
print first ten integers

Printing a greeting is as simple as

<<print greeting>>=
printf "Hello World!"

Ruby has a for-loop so print first ten integers can be implemented (using a range) like this:

for i in 1..10 {
  printf i

But the use of an iterator and a closure is more idiomatic:

<<print first ten integers>>=
(1..10).each { i ->
  printf i

Groovy is a scripting language so there is no compiler. To run the program you simply fire up the ruby interpreter and pass it the script:

$ groovy HelloWorld.groovy
Hello World!

Groovy is also an object-oriented language which contains classes. The hello world program as a class would be

class HelloWorld {
  def greet() {
     print greeting
  def printFirstTenIntegers() {
     print first ten integers

The class can be loaded, instantiated and executed inside the interpreter like this:


or in a script, like this:

import HelloWorldClass

hw = new HelloWorld()

[edit] References

Download code