Hello World (Groovy)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Ada | ALGOL 68 | Alice ML | Amiga E | Applescript | AspectJ | Assembly Intel x86 Linux | Assembly Intel x86 NetBSD | AWK | bash | BASIC | Batch files | C | C, Cairo | C, Xlib | Candle | Clojure | C++ | C# | Delphi | Dylan | E | Eiffel | Erlang | Forth | FORTRAN | Fortress | Go | Groovy | Haskell | Hume | IBM PC bootstrap | Inform 7 | Java | Java, Swing | JavaScript | LaTeX | Lisp | Logo | Lua | Maple | MATLAB | Mercury | OCaml/F Sharp | occam | Oz | Pascal | Perl | PHP | Pic | PIR | PLI | PostScript | Prolog | Python | Rexx | Ruby | Scala | Scheme | Seed7 | sh | Smalltalk | SQL | Standard ML | SVG | Tcl | Tcl Tk | Visual Basic | Visual Basic .NET | XSL

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.

<<HelloWorld.groovy>>=
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: (besides that, can use either print i or printf "%d",i)

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

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

$ groovy HelloWorld.groovy
Hello World!
1
2
3
4
5
6
7
8
9
10

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

<<HelloWorldClass.groovy>>=
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()
hw.greet()
hw.printFirstTenIntegers()

References

  • Groovy Language Home Page.
  • Wikipedia entry on the Groovy programming language
Download code
Views
Personal tools