NETB131 Programming Project
Programming language Groovy
An overview


Lazar Eduardov Lazarov, F39654

Navigation:
1. History and Special Features
2. "Hello World" Program
3. Fundamental Data Types and Assignment Operators
4. Basic Control Flow
5. Functions
6. Arrays
7. Compilers
8. Projects and software in Groovy
9. Standard
10. References


1. History and Special Features (^)
James Strachan first talked about the development of Groovy in his blog in August 2003. Several versions were released between 2004 and 2006. After the JCP(Java Community Process) standardization process began, the version numbering was changed and a version called "1.0" was released on Tuesday, January 2, 2007.

Groovy is an object-oriented programming language for the Java Platform as an alternative to the Java programming language. It can be viewed as a scripting language for the Java Platform, as it has features similar to those of Python, Ruby, Perl, and Smalltalk. In some contexts, the name JSR 241 is used as an alternate identifier for the Groovy language.

Groovy ...

2. "Hello World" Program (^)
      
println "Hello World"

3. Fundamental Data Types (integer, floating point, string, boolean, list, map) and Assignment Operators (^)
Definitions:

//This is a comment. Semicolons are optional. Use them if you like (though you must use them to put several statements on one line)
//def to define a variable and give it a value
def x = 1 //creates an integer
def y = "Hi"; def z = 0.1 //will create a string and a floating point
def myBooleanVariable = true //creates a boolean
def myList = [1776, -1, 33, 99, 0, 928734928763] //to create a list AKA array
def scores = [ "Brett":100, "Pete":"Did not finish", "Andrew":86.87934 ] //to create a map AKA dictionary

 'A string can be within single quotes on one line...'
'''...or within triple single quotes
over many lines, ignoring // and /* and */ comment delimiters,...'''
"...or within double quotes..."
"""...or within triple double quotes
over many lines."""

variable = expression // the = operator assigns the value of the expression on the right to the variable on the left.
assert expression == expression /*is used for debugging and understanding of code. It DOES NOT change anything.
If the assert is true, do nothing. If it is false, terminate the program, displaying the file/script name, line number,
expression and where is the error. It is similar to the assert (expression) macro in C++ */

x = -3.1499392
a = 'world'
assert 4+1 == 6-1

Other assigments are supported:

def test = 5
test += 5
assert test == 10 // test is now 10
test -= 5
assert test == 5 // now test is 5 again
test *= 5
assert test == 25 // now it is 25
test /=5
assert test == 5 // test is back to its initial value

Groovy supports bitwise operations:

assert (1 << 2) == 4 // bitwise left shift
assert (4 >> 1) == 2 // bitwise right shift
assert (15 >>> 1) == 7 // bitwise unsigned right shift
assert (3 | 6) == 7 // bitwise or
assert (3 & 6) == 2 // bitwise and
assert (3 ^ 6) == 5 // bitwise xor
assert (~0xFFFFFFFE) == 1 // bitwise negation

4. Basic Control Flow (conditional and loop statements) (^)
Conditional operators if and if-else

if (condition) {code to execute}
// optional
else {code to execute}

Example:

amPM = Calendar.getInstance().get(Calendar.AM_PM)
if (amPM == Calendar.AM)
{
    println("Good morning")
} else {
    println("Good evening")
}

Conditional operator switch:

switch (expression) {
    case 'c1':
    //code to execute
    break
    case 'c2':
    //code to execute
    break
    default:
             //code to execute
}

Example:
def years = 20
switch (years) {
case 1..10: interestRate = 0.076; break;
case 11..25: interestRate = 0.052; break;
default: interestRate = 0.037;
}
println interestRate

Loop operator while:

while (condition) {code to execute}

Example:
int n=1
while( n <= 5 ){
  def y = 0
  (1..n).each{ //loop variable, here 'it', not available outside loop
    y += it
  }
  assert y == (n+1)*(n/2.0) //another way to add the numbers 1 to n
  n++
}

Loop operator for:

for ( condition ) { code to execute }

Example:
list = []
for ( i in 1..9 ) { //iterate over a range
  list<< i
}
print list

Task: Input an integer number n and output the sum: 1+22+32+...+n2. Use input validation for n to be positive.

          //using number instead of n for better readability
input = new Scanner(System.in)
number = input.nextInt()
if (number > 0) {
    def sum = 0
    for ( i in 1..number) {
      sum = i*i + sum
    }
    print sum
} else { println "Negative number or zero"}

5. Functions (^)

This is how we declare a function:

def functionName(parameter1,parameter2,etc) { code to execute }

Here is a simple example:

def fac(n) { n == 0 ? 1 : n * fac(n - 1) } //do not forget Groovy is a freeform language, every statement can be on its own line if you wish
assert fac(4) == 24

6. Arrays (^)

I already gave a simple example of an array in the beginning of the project (under Fundamental Data Types). Here are some other ways to introduce arrays in Groovy.

def a = new Object[4] //we must specify the size of the fixed-size array
a[0] = 'a'
a[1] = 2 //elements can be any value
a.putAt(2, 'c') //alternative method name syntax
a[3] = false

We can specify the initial collection of contained objects when we construct the array. Those objects can be any other entity in Groovy, eg, numbers, boolean values, characters, strings, regexes, lists, maps, closures, expandos, classes, class instances, or even other object arrays:

someList = [ 14.25, 17g, [1,2,3], 'Hello, world', ['a', false, null, 5], new Object[200], 6*6]

This is how we create a multidimensional array and output its values:

def m = new Object[3][3]
println m // this will just show what is in the array

(0..<m.size()).each{i->
(0..<m[i].size()).each{j->
print m[i][j] // this outputs each value one by one
}
}

7. Compilers (^)

The compiler for groovy is called groovyc and it comes with the groovy installation(download). It takes a bunch of groovy source files and compiles them into Java bytecode. Each groovy class then just becomes a normal Java class you can use inside your Java code if you wish. Indeed the generated Java class is indistinguishable from a normal Java class, other than it implements the GroovyObject interface.

Alternatively if you don't want to explicitly compile groovy code to bytecode you can just embed groovy directly into your Java application.

8. Projects and software in Groovy (^)

Groovy 1.0 came in January 2007. It is a new language and not much software can be found written in it. Also consider it is a scripting language generating Java bytecode. I am sure it is already a part of some big Java projects but it would be hard to identify and tell where exactly. However here is a small list of modules written in and/for Groovy.

9. Standard (^)

Groovy is influenced by Python, Ruby and Java so any standard applied to those languages can be used when coding in Groovy. But this defeats the purpose of creating Groovy - it is made to be efficent, freeform language with minimal syntax requirements so that any programmer can comfortly fit his own coding style in it.

10. References (^)

  1. Groovy on Wikipedia
  2. Groovy on Codehaus.org
  3. Groovy documentation