Showing posts with label Groovy. Show all posts
Showing posts with label Groovy. Show all posts

Tuesday, December 2, 2014

Arrays and Indexers in Groovy



Today's post is about Arrays and Indexers in Groovy. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in Groovy, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

By the way, if you missed my (not so) recent post (anymore), "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in Java just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.


package groovyarrays

// Single-dimensional Array(s)  
printTitle("Reverse Array Elements")  

// Declare and Initialize Array of Chars  
def letters = new char[5] 
letters[0] = 'A'  
letters[1] = 'E'  
letters[2] = 'I'  
letters[3] = 'O'  
letters[4] = 'U'  

printArray letters
def inverse_letters = reverseChar letters
printArray inverse_letters

printTitle "Sort Integer Array Elements"

// Declare and Initialize Array of Integers
def numbers = [ 10, 8, 3, 1, 5 ].toArray()
printArray numbers
def ordered_numbers = bubbleSort numbers
printArray ordered_numbers

printTitle "Sort String Array Elements"

// Declare and Initialize and Array of Strings
def names = [                       
    "Damian",   
    "Rogelio",  
    "Carlos",   
    "Luis",                       
    "Daniel"
    ].toArray()
printArray names
def ordered_names = bubbleSort names  
printArray ordered_names 

// Multi-dimensional Array (Matrix row,column)  

printTitle "Transpose Matrix"  

/* Matrix row=2,col=3 
 * A =  [6  4 24] 
 *      [1 -9  8] 
*/  
def matrix = [[6, 4, 24] as int[],
              [1, -9, 8] as int[]] as int[][]

printMatrix matrix
def transposed_matrix = transposeMatrix matrix
printMatrix transposed_matrix

// Jagged Array (Array-of-Arrays)

printTitle "Upper Case Random Array & Graph Number of Elements"

/*              
 * Creating an array of string arrays using the String.Split method 
 * instead of initializing it manually as follows: 
 *  
 * def text1 = [ 
 *      [ "word1", "word2", "wordN" ].toArray() as String[],   
 *      [ "word1", "word2", "wordM" ].toArray() as String[]  
 *      ... 
 *      ].toArray() as String[]
 *  
 * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
 *  
 */  
def text = [   
"Hoy es el día más hermoso de nuestra vida, querido Sancho;".split(" "),  
"los obstáculos más grandes, nuestras propias indecisiones;".split(" "),  
"nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".split(" "),  
"la cosa más fácil, equivocarnos;".split(" "),  
"la más destructiva, la mentira y el egoísmo;".split(" "),  
"la peor derrota, el desaliento;".split(" "),  
"los defectos más peligrosos, la soberbia y el rencor;".split(" "),  
"las sensaciones más gratas, la buena conciencia...".split(" ")   
].toArray()

printJaggedArray text  
upperCaseRandomArray text  
printJaggedArray text
graphJaggedArray text  

// Array Exceptions  

printTitle "Common Array Exceptions"

printCommonArrayExceptions null
printCommonArrayExceptions text  

// Accessing Class Array Elements through Indexer  

printTitle "Alphabets"

def vowels = new Alphabet(5)  
vowels[0] = 'a'  
vowels[1] = 'e'  
vowels[2] = 'i'  
vowels[3] = 'o'  
vowels[4] = 'u'  
        
println "\nVowels = {${[vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]].join(",")}}"                   

def en = new Alphabet("abcdefghijklmnopqrstuvwxyz") 
println "English Alphabet = {${en.toString()}}" 

println "Alphabet Extract en[9..19] = {${new Alphabet(en.slice(9, 10))}}"

word1 = [en[6], en[14], en[14], en[3]].toArray().join('')
word2 = [en[1], en[24], en[4]].toArray().join('')
word3 = [en[4], en[21], en[4], en[17], 
         en[24], en[14], en[13], en[4]].toArray().join('')

println "\n$word1 $word2, $word3!"  


def reverseChar(arr) {
    arr.toList().reverse().toArray() as char[]
    /* // or...
    def reversed = new char[arr.length]
    j = arr.length-1
    for (i in 0..<arr.length) {
        reversed[i] = arr[j]
        j--
    }
    reversed
    */
}

def bubbleSort(arr) {
    swap = 0
    for (int i = arr.length - 1; i > 0; i--)
        for (int j = 0; j < i; j++)
            if (arr[j] > arr[j + 1]) {
                swap = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = swap;
            }
    arr
}

def transposeMatrix(m) {
    /* Transposing a Matrix 2,3
     *
     * A =  [6  4 24]T [ 6  1]
     *      [1 -9  8]  [ 4 -9]
     *                 [24  8]
    */
    def transposed = new int[m[0].length][m.length]
    for (i in 0..<m.length)
        for (j in 0..<m[0].length)
            transposed[j][i] = m[i][j]   
    transposed
}

def upperCaseRandomArray(arr) {  
    def r = new Random() 
    int i = r.nextInt arr.length 
    for (j in 0..<arr[i].length) 
        arr[i][j] = arr[i][j].toUpperCase()
}

def printArray(arr) {
    println "\nPrint Array Content ${arr.getClass().getName()}[$arr.length]"
    for (i in 0..<arr.length)
        println sprintf(" array [% 2d] = %2s", i, arr[i])
}

def printMatrix(m) {
    println sprintf("\nPrint Matrix Content %s[%d,%d]",
        m.getClass().getName(), m.length, m[0].length)

    for (int i = 0; i < m.length; i++)
        for (int j = 0; j < m[0].length; j++)
            println sprintf(" array [%2d,%2d] = %2s", i, j, m[i][j].toString())
}

def graphJaggedArray(arr) {  
    /* When using Arrays, we can use foreach instead of for:  
     *  
     * for (i in 0..<arr.length) 
     *   for (j in 0..<arr.length)                 
     *  
    */  
    println "\nPrint Text Content ${arr.getClass().getName()}"  
    lineCount = 1  
    for(s in arr) {  
        print sprintf("Line%2s|", lineCount)
        for(w in s) 
            print sprintf("%3s", '*')
        println sprintf(" (%d)", s.length)  
        lineCount++
    }  
}  

def printJaggedArray(arr) {
    println "\nPrint Jagged Array Content ${arr.getClass().getName()}"
    for (i in 0..<arr.length) {
        def line = new StringBuffer()
        for (j in 0..<arr[i].length) 
            line.append(" ").append(arr[i][j])
        if (line.toString().equals(line.toString().toUpperCase())) 
            line.append(" <-- [UPPERCASED]")
        println line
    }
}

def printCommonArrayExceptions(arr) {  
    try {  
        arr[100][100] = "hola" 
    }  
    catch (ex) {  
        println "\nException: \n${ex.getClass().getName()}\n${ex.getMessage()}"                
    }  
}  

def printTitle(message) {
    println ""
    println "=" * 54
    println message
    println "=" * 54
}


class Alphabet {
    // Array Field
    private char[] letters

    // Indexer Getter/Setter 
    def getAt(int index) {
        letters[index]
    }    
    def putAt(int index, def value) {
       letters[index] = value.toUpperCase()
    }

    // Getter
    def getLength() {  
        letters.length
    }  
  
    // Constructors  
    public Alphabet(int size) {  
        letters = new char[size]
    }  

    public Alphabet(String list) {  
        letters = list.toUpperCase().toCharArray()
    }  

    public Alphabet(char[] list) {  
        letters = list
    }  
    
    // Overridden Method  
    @Override
    String toString() {  
        letters.toString().split("").join(",")
    }  
    
    // Method  
    def slice(int start, int length) {  
        letters[start..<start+length].toArray() as char[]
    }  
}


The output:








Voilà, that's it. Next post in the following days.

Friday, January 20, 2012

Factorial and Fibonacci in Groovy



Here below a little program in Groovy that implements 2 classes (in fact, they are 3 + an extra utility Stopwatch class from my previous post http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "main".

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including java.math.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 


The Fiborial Program

// Factorial and Fibonacci in Groovy  
package com.series  
import java.math.BigInteger  
  
// Instance Class  
class StaticFiborial    
{      
    // Static Field      
    private static className  
    // Class/Static Constructor/Initializer    
    static    
    {      
        className = "Static Constructor"  
        println className  
    }      
    // Class/Static Method - Factorial Recursive      
    static factorialR(int n)      
    {      
        if (n == 1)      
            return BigInteger.ONE  
        else      
            return n * factorialR(n - 1)  
    }      
    // Class/Static Method - Factorial Imperative      
    static factorialI(int n)      
    {      
        def res = BigInteger.ONE  
        for (int i = n; i >= 1; i--)      
        {                      
            res *= i  
        }      
        return res  
    }      
    // Class/Static Method - Fibonacci Recursive      
    static fibonacciR(int n)      
    {      
        if (n < 2)      
            return 1  
        else      
            return fibonacciR(n - 1) + fibonacciR(n - 2)  
    }      
    // Class/Static Method - Fibonacci Imperative      
    static fibonacciI(int n)      
    {                  
        def pre, cur, tmp = 0  
        pre = cur = 1          
        for (i in 2..n)  
        {      
            tmp = cur + pre  
            pre = cur  
            cur = tmp  
        }      
        return cur    
    }          
    // Class/Static Method - Benchmarking Algorithms      
    static benchmarkAlgorithm(algorithm, values)      
    {                  
        def timer = new Stopwatch()  
        def i, testValue  
        def facTimeResult = BigInteger.ZERO  
        def fibTimeResult = 0  
        i = testValue = 0              
              
        // "Switch" Flow Control Statement      
        switch (algorithm)      
        {      
            case 1:      
                println "\nFactorial Imperative:"  
                // "For" Loop Statement      
                for (i = 0; i < values.size(); i++)      
                {                              
                    testValue = ((Integer)values.get(i)).intValue()  
                    // Taking Time      
                    timer.start()  
                    facTimeResult = factorialI(testValue)  
                    timer.stop()      
                    // Getting Time      
                    println " ($testValue) = ${timer.getElapsed()}"  
                }                          
                break      
            case 2:      
                println "\nFactorial Recursive:"  
                // "While" Loop Statement      
                while (i < values.size())      
                {                              
                    testValue = ((Integer)values.get(i)).intValue()  
                    // Taking Time      
                    timer.start()  
                    facTimeResult = factorialR(testValue)  
                    timer.stop()  
                    // Getting Time      
                    println " ($testValue) = ${timer.getElapsed()}"  
                    i++  
                }      
                break     
            case 3:      
                println "\nFibonacci Imperative:"  
                // "For" Loop Statement      
                for (j in 0..values.size()-1)  
                {   
                    testValue = ((Integer)values.get(j)).intValue()  
                    // Taking Time  
                    timer.start()  
                    fibTimeResult = fibonacciI(testValue)  
                    timer.stop()  
                    // Getting Time      
                    println " ($testValue) = ${timer.getElapsed()}"                      
                }                  
                break  
            case 4:      
                println "\nFibonacci Recursive:"  
                // "For Each" Loop Statement                      
                for (item in values)  
                {      
                    testValue = item  
                    // Taking Time      
                    timer.start()    
                    fibTimeResult = fibonacciR(testValue)  
                    timer.stop()  
                    // Getting Time  
                    println " ($testValue) = ${timer.getElapsed()}"  
                }   
                break  
            default:      
                println "DONG!"  
                break  
        }   
    }      
}  
  
// Instance Class      
class InstanceFiborial      
{      
    // Instance Field      
    private def className  
    // Instance Constructor      
    def InstanceFiborial()      
    {      
        this.className = "Instance Constructor"  
        println this.className  
    }      
    // Instance Method - Factorial Recursive      
    def factorialR(n)      
    {      
        // Calling Static Method      
        return StaticFiborial.factorialR(n)  
    }      
    // Instance Method - Factorial Imperative      
    def factorialI(n)      
    {      
        // Calling Static Method      
        return StaticFiborial.factorialI(n)      
    }      
    // Instance Method - Fibonacci Recursive  
    def fibonacciR(n)      
    {      
        // Calling Static Method      
        return StaticFiborial.fibonacciR(n)  
    }      
    // Instance Method - Factorial Imperative      
    def fibonacciI(n)      
    {      
        // Calling Static Method      
        return StaticFiborial.fibonacciI(n)  
    }      
}    
  
  
println "\nStatic Class"      
// Calling Static Class and Methods  
// No instantiation needed. Calling method directly from the class      
println "FacImp(5) = ${StaticFiborial.factorialI(5)}"  
println "FacRec(5) = ${StaticFiborial.factorialR(5)}"      
println "FibImp(11)= ${StaticFiborial.fibonacciI(11)}"      
println "FibRec(11)= ${StaticFiborial.fibonacciR(11)}"  
  
println "\nInstance Class"      
// Calling Instance Class and Methods       
// Need to instantiate before using. Calling method from instantiated object      
def ff = new InstanceFiborial()  
println "FacImp(5) = ${ff.factorialI(5)}"  
println "FacRec(5) = ${ff.factorialR(5)}"  
println "FibImp(11)= ${ff.fibonacciI(11)}"  
println "FibRec(11)= ${ff.fibonacciR(11)}"  
  
// Create a list of integer values to test  
// From 5 to 50 by 5      
def values = []  
5.step(55, 5) {  
    values.add(it)  
}  
  
// Benchmarking Fibonacci                           
// 1 = Factorial Imperative                  
StaticFiborial.benchmarkAlgorithm(1, values)  
// 2 = Factorial Recursive      
StaticFiborial.benchmarkAlgorithm(2, values)  
  
// Benchmarking Factorial                  
// 3 = Fibonacci Imperative      
StaticFiborial.benchmarkAlgorithm(3, values)  
// 4 = Fibonacci Recursive      
StaticFiborial.benchmarkAlgorithm(4, values)  
  
// Stop and exit      
println "Press any key to exit..."    
def sin = new Scanner(System.in)    
def line = sin.nextLine()    
sin.close()

And the Output is:























































Printing the Factorial and Fibonacci Series
package com.series  
import java.math.BigInteger    
import java.lang.StringBuffer  
    
class Fiborial    
{    
    // Using a StringBuffer as a list of string elements    
    static getFactorialSeries(n)    
    {    
        // Create the String that will hold the list    
        def series = new StringBuffer()  
        // We begin by concatenating the number you want to calculate    
        // in the following format: "!# ="    
        series.append("!")  
        series.append(n)  
        series.append(" = ")  
        // We iterate backwards through the elements of the series    
        for (i in n..0)  
        {    
            // and append it to the list    
            series.append(i)  
            if (i > 1)  
                series.append(" * ")  
            else     
                series.append(" = ")  
        }  
        // Get the result from the Factorial Method    
        // and append it to the end of the list    
        series.append(factorial(n))    
        // return the list as a string    
        return series
    }    
    
    // Using a StringBuffer as a list of string elements    
    static getFibonnaciSeries(n)    
    {    
        // Create the String that will hold the list    
        def series = new StringBuffer();    
        // We begin by concatenating the first 3 values which    
        // are always constant    
        series.append("0, 1, 1")  
        // Then we calculate the Fibonacci of each element    
        // and add append it to the list    
        for (i in 2..n)  
        {    
            if (i < n)    
                series.append(", ")  
            else    
                series.append(" = ")  
                
            series.append(fibonacci(i))  
        }    
        // return the list as a string    
        return series    
    }    
    
    static factorial(n)    
    {    
        if (n == 1)      
            return BigInteger.ONE  
        else      
            return n * factorial(n - 1)  
    }            
    
    static fibonacci(n)    
    {    
        if (n < 2)      
            return 1  
        else      
            return fibonacci(n - 1) + fibonacci(n - 2)  
    }       
}    
  
  
// Printing Factorial Series    
println ""
println Fiborial.getFactorialSeries(5)    
println Fiborial.getFactorialSeries(7)  
println Fiborial.getFactorialSeries(9)  
println Fiborial.getFactorialSeries(11)  
println Fiborial.getFactorialSeries(40)  
// Printing Fibonacci Series    
println ""  
println Fiborial.getFibonnaciSeries(5)  
println Fiborial.getFibonnaciSeries(7)  
println Fiborial.getFibonnaciSeries(9)  
println Fiborial.getFibonnaciSeries(11)  
println Fiborial.getFibonnaciSeries(40)

And the Output is:
















Mixing Instance and Static Members in the same Class

Instance classes can contain both, instance and static members such as: fields, getters/setters, constructors/initializers, methods, etc.

package com.series

// Instance Class    
class Fiborial    
{    
    // Instance Field    
    private def instanceCount    
    // Static Field    
    private static staticCount
    // Instance Read-Only Getter    
    // Within instance members, you can always use      
    // the "this" reference pointer to access your (instance) members.    
    def getInstanceCount()  
    {    
        return this.instanceCount     
    }    
    // Static Read-Only Getter        
    // As with Static Methods, you cannot reference your class members    
    // with the "this" reference pointer since static members are not    
    // instantiated.            
    static getStaticCount()  
    {    
        return staticCount    
    }    
    // Instance Constructor    
    def Fiborial()    
    {    
        this.instanceCount = 0
        println "\nInstance Constructor ${this.instanceCount}"
    }    
    // Static Constructor    
    static
    {    
        staticCount = 0;    
        println "\nStatic Constructor $staticCount"    
    }    
  
    // Instance Method    
    def factorial(n)    
    {    
        this.instanceCount += 1
        println "\nFactorial($n)"
    }    
  
    // Static Method    
    static fibonacci(n)    
    {    
        staticCount += 1    
        println "\nFibonacci($n)"
    }                    
}  

// Calling Static Constructor and Methods    
// No need to instantiate    
Fiborial.fibonacci(5)

// Calling Instance Constructor and Methods
// Instance required    
def fib = new Fiborial()
fib.factorial(5)           

Fiborial.fibonacci(15)
fib.factorial(5)

// Calling Instance Constructor and Methods    
// for a second object    
def fib2 = new Fiborial()
fib2.factorial(5)

println ""
// Calling Static Property    
println "Static Count = ${Fiborial.getStaticCount()}}"
// Calling Instance Property of object 1 and 2    
println "Instance 1 Count = ${fib.getInstanceCount()}"
println "Instance 2 Count = ${fib2.getInstanceCount()}"

And the Output is:



















Factorial using java.lang.Long, java.lang.Double, java.math.BigInteger


package com.series    
import java.math.BigInteger  
      
// Long Factorial      
long factorialInt64(n)      
{      
    if (n == 1)      
        return 1    
    else      
        return n * factorialInt64(n - 1)    
}    
  
// Double Factorial    
double factorialDouble(n)      
{      
    if (n == 1)      
        return 1  
    else      
        return n * factorialDouble(n - 1)  
}    
  
// BigInteger Factorial     
BigInteger factorialBigInteger(n)      
{      
    if (n == 1)      
        return BigInteger.ONE  
    else      
        return n * factorialBigInteger(n - 1)
}    
  
def timer = new Stopwatch()  
long facIntResult = 0     
double facDblResult = 0  
def facBigResult = BigInteger.ZERO      
  
println "\nFactorial using Int64"  
// Benchmark Factorial using Int64      
for (i in (5..50).step(5)) {      
    timer.start()  
    facIntResult = factorialInt64(i)  
    timer.stop()      
    println " ($i) = ${timer.getElapsed()} : ${facIntResult}"    
}      
println "\nFactorial using Double"  
// Benchmark Factorial using Double      
for (i in (5..50).step(5)) {      
    timer.start()  
    facDblResult = factorialDouble(i)  
    timer.stop()  
    println " ($i) = ${timer.getElapsed()} : ${facDblResult}"  
}      
println "\nFactorial using BigInteger"  
// Benchmark Factorial using BigInteger      
for (i in (5..50).step(5)) {      
    timer.start()  
    facBigResult = factorialBigInteger(i)  
    timer.stop()  
    println " ($i) = ${timer.getElapsed()} : ${facBigResult}"              
}

And the Output is:


Friday, October 29, 2010

Groovy - Basics by Example



Continue with the Basics by Example; today's version of the post written in Groovy Enjoy!

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
// Groovy Basics
package GvyGreetProgram

public class Greet {
    // Fields or Attributes
    private String message
    private String name
    private Integer loopMessage    
    // Properties or Getters and Setters
    public String getMessage() {  
        return this.message
    }  
    public void setMessage(String val) {  
        this.message = this.Capitalize(val)
    }  
    public String getName() {  
        return this.name
    }  
    public void setName(String val) {  
        this.name = this.Capitalize(val) 
    }  
    public Integer getLoopMessage() {  
        return this.loopMessage
    }  
    public void setLoopMessage(Integer val) {
        this.loopMessage = val
    }
    // Constructor  
    public def Greet() {  
        this.message = ""
        this.name = ""
        this.loopMessage = 0
    }  
    // Overloaded Constructor  
    public def Greet(String message, String name, Integer loopMessage) {  
        this.message = this.Capitalize(message)
        this.name = this.Capitalize(name)
        this.loopMessage = loopMessage
    }
    // Method 1
    private String Capitalize(String val) {  
        // "if-then-else" statement  
        if (val.size() >= 1) {  
            return val[0].toUpperCase() + val[1..-1]  
        }  
        else  {  
            return "";  
        }  
    }  
    // Method 2  
    public void Salute() {  
        // "for" statement  
        for (i in 1..this.loopMessage) {  
            println "${this.message} ${this.name}!"  
        }  
    }  
    // Overloaded Method 2.1  
    public void Salute(String message, String name, Integer loopMessage) {  
        // "while" statement  
        Integer i = 0
        while(i < loopMessage) {  
            println "${this.Capitalize(message)} ${this.Capitalize(name)}!" 
            i++  
        }  
    }  
    // Overloaded Method 2.2  
    public void Salute(String name) {  
        // "switch/case" statement  
        def dtNow = new GregorianCalendar()
        switch (dtNow.get(Calendar.HOUR_OF_DAY))  
        {  
            case 6: case 7: case 8: case 9: case 10: case 11:  
                this.message = 'good morning,' 
                break;  
            case 12: case 13: case 14: case 15: case 16: case 17:  
                this.message = 'good afternoon,'
                break;  
            case 18: case 19: case 20: case 21: case 22:  
                this.message = 'good evening,' 
                break;  
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                this.message = 'good night,'
                break;  
            default:  
                this.message = 'huh?' 
                break;  
        }  
        println "${this.Capitalize(this.message)} ${this.Capitalize(name)}!"
    } 
}  

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor  
Greet g = new Greet()
// Call Setters  
g.setMessage('hello')
g.setName('world')
g.setLoopMessage(5)
// Call Method 2  
g.Salute()
// Overloaded Method 2.1 and Getters  
g.Salute(g.getMessage(), 'groovy', g.getLoopMessage()) 
// Overloaded Method 2.2  
g.Salute('carlos')

// Stop and exit  
println "Press any key to exit..."
Scanner sin = new Scanner(System.in)
String line = sin.nextLine()
sin.close()

Greetings Program - Minimal
// Groovy Basics
class Greet {
    // Fields or Attributes
    private def message
    private def name
    private def loopMessage    
    // Properties or Getters and Setters
    def getMessage() {  
        return message
    }  
    def setMessage(val) {  
        message = Capitalize(val)
    }  
    def getName() {  
        return name
    }  
    def setName(val) {  
        name = Capitalize(val) 
    }  
    def getLoopMessage() {  
        return loopMessage
    }  
    def setLoopMessage(val) {
        loopMessage = val
    }
    // Constructor  
    def Greet() {  
        message = ""
        name = ""
        loopMessage = 0
    }  
    // Overloaded Constructor  
    def Greet(message, name, loopMessage) {  
        this.message = Capitalize(message)
        this.name = Capitalize(name)
        this.loopMessage = loopMessage
    }
    // Method 1
    private def Capitalize(val) {  
        // "if-then-else" statement  
        if (val.size() >= 1) {  
            return val[0].toUpperCase() + val[1..-1]  
        }  
        else  {  
            return "";  
        }  
    }  
    // Method 2  
    def Salute() {  
        // "for" statement
        for (i in 1..loopMessage) {  
            println "$message $name!"  
        }  
    }  
    // Overloaded Method 2.1  
    def Salute(message, name, loopMessage) {  
        // "while" statement  
        def i = 0
        while(i < loopMessage) {  
            println "${Capitalize(message)} ${Capitalize(name)}!" 
            i++  
        }  
    }  
    // Overloaded Method 2.2  
    def Salute(name) {  
        // "switch/case" statement  
        def dtNow = new GregorianCalendar()
        switch (dtNow.get(Calendar.HOUR_OF_DAY))  
        {  
            case 6: case 7: case 8: case 9: case 10: case 11:  
                message = 'good morning,'
                break;  
            case 12: case 13: case 14: case 15: case 16: case 17:  
                message = 'good afternoon,' 
                break;  
            case 18: case 19: case 20: case 21: case 22:  
                message = 'good evening,' 
                break;  
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                message = 'good night,'
                break;  
            default:  
                message = 'huh?'
        }  
        println "${Capitalize(message)} ${Capitalize(name)}!"
    } 
}  

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor  
def g = new Greet()
// Call Setters  
g.setMessage('hello')
g.setName('world')
//g.setLoopMessage(5)
g.loopMessage = 5
// Call Method 2  
g.Salute()
// Overloaded Method 2.1 and Getters  
g.Salute(g.getMessage(), 'groovy', g.getLoopMessage())
// Overloaded Method 2.2  
g.Salute('carlos')

// Stop and exit  
println "Press any key to exit..."
def sin = new Scanner(System.in)
def line = sin.nextLine()
sin.close()


And the Output is:


















Auto-Implemented Properties in Groovy
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The following code shows how to use them just like with VB.NET, C#, C++/CLI and so on.

class Greet {  
    // Fields or Attributes
    // and Autoimplemented Properties (Getters and Setters)
    // To create auto implemented setters and getters you just define the fields with no explicit accessor
    String message = 'empty_message'
    def name = 'empty_name'
    Integer loopMessage = 0
    // if you specify an explicit accessor then you need to define your own explicit Setters and Getters
    // as I did in the minimal and verbose examples (because we needed the capitalize custom code in set properties)
    // Example:
    // public String message = 'empty_message'
    // private def name = 'empty_name'
    // protected Integer loopMessage = 0
    // The only one that will still create an auto-implemented Setter will be "final", but no setter since
    // that's how you do a read-only property.
    def Salute() {
        println "$message $name $loopMessage"
    }
} 
  

g = new Greet()
g.Salute()  
// Calling Auto-implemented Setters
g.setMessage('hello')
g.setName('world')
g.setLoopMessage(5)
g.Salute()  
// we can also access the fields from the class directly
g.message = 'bye'
g.name = 'carlos'
g.loopMessage = 2
// Calling Auto-implemented Getters
println g.getMessage() + ' ' + g.getName() + ' ' + g.getLoopMessage()


And the Output is:



Wednesday, June 30, 2010

OO Hello World - Groovy



The Hello World version of the program in Groovy! A dynamic language for the JVM runtime with a very Java-like syntax.


By the way, you can see my previous post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html
where I give some details on WHY these "OO Hello World series" samples.


Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.

class Greet {
  def name
  Greet(name) { 
      this.name = name[0].toUpperCase() + name[1..-1]
  }
  def salute() { 
      println "Hello $name!"
  }
}

// Greet the world! 
g = new Greet('world')  
g.salute()

Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.

package GreetProgram

private class Greet {
  private def name
  public def Greet(name) { 
      this.name = name[0].toUpperCase() + name[1..-1]
  }
  public def salute() { 
      println "Hello $name!"
  }
}

// Greet the world! 
g = new Greet('world')  
g.salute()

The Program Output:









Groovy Info:
“Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform.
Groovy uses a Java-like bracket syntax. It is dynamically compiled to Java Virtual Machine bytecode and interoperates with other Java code and libraries. Most Java code is also syntactically valid Groovy.” Taken from: (http://en.wikipedia.org/wiki/Groovy_(programming_language))

Appeared:
2003
Current Version:
1.7.5 and 1.8 Beta 2  (latest version in "Languages" page
Developed by:
Guillaume Laforge
Creator:
Guillaume Laforge
Influenced by:
Java (James Gosling)
Predecessor Language
Predecessor Appeared
Predecessor Creator
Runtime Target:
JVM
Latest Framework Target:
JDK 6
Mono Target:
No
Allows Unmanaged Code:
No
Source Code Extension:
“.groovy”
Keywords:
57
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:
JSR 241
Latest IDE Support:
NetBeans
Eclipse
IntelliJ IDEA
Language Reference:
Extra Info: