• 31 Jul-13

    In this blog first I am looking into two languages Java and Groovy both are JDK based languages . Java is strongly and statically typed language whereas Groovy is dynamically and optionally typed language .

    The best things about groovy is

    What I love about groovy is that Since it extends JDK , it accepts the java code . You’ll see that your code is doing the same things, but it’s a lot smaller.

    With Groovy we have power of Java too .

    Let us see see some features of Groovy and we compare it with Java .



    • It follows Java semantics.
    • It is dynamic language.
    • It extends the JDK.
      • Loop

        In java if we have to iterate using for Loop our code will be like this

        for(int i=0;i<=4;i++){

        In above code there is declaration and initialization of variable , there is comparision with every iteration and increment operator

        In Groovy , we could do same thing in following ways

        for(j in 0..4){print j}
        0.upto(3) {print "$it"}
        4.times{print "$it"}

        Now if we want to print 0,2,4,6,8 and 10 using for loop , what we will do in Java is

        for(int i=0;i<=10;i=i+2){

        And in groovy

        0.step(10,2){print "$it"} 
        2. System level process in Groovy and Java 
      • System-level Process

        In Java,we can use java.lang.Process to interact with a system-level process. let us see the Java code

        Process proc = Runtime.getRuntime().exec("ls -l" );
        BufferedReader result = new BufferedReader(
        new InputStreamReader(proc.getInputStream()));
        String line;
        while((line = result.readLine()) != null)
        catch(IOException ex)

        In above code we are executing linux command ls -l and then reading the output using BufferedReader and print the output of ls -l on console

        In groovy you can simply print

        println "ls -l".execute().text
        println "ls -l".execute().getClass().name

        The output from the previous code, when run on a Unix-like machine, is as follows:


        On a Windows machine, you’ll get this:

      • Safe Navigation Operator

        In Java if we want to perform some operation on null object , what we will get null pointer exception on console . To avoid this , ‘if’ condition will come to our rescue .

        String myString = null ;
        if(myString != null){
        println myString.reverse()

        In groovy we can simply use

        println myString?.reverse()

        Output we will get in this case is null

      • A look at Exception Handling in Java and Groovy

        Java forces us to handle checked exceptions.if we use Thread’s sleep( ) method. Java will force us to catch java.lang.InterruptedException.

        catch(InterruptedException ex)

        What if we want to suppress the exception . We will simply add an empty catch block . Having an empty catch block is worse than not handling an exception. Exception is propagated to the caller who either can do something about it or can pass it yet again to its caller.

        Now a lot of empty catch blocks will make our code look dirtier .Groovy does not force programmer to handle exceptions that he/she don’t want to handle or that are inappropriate at his/her level. Any exception we don’t handle is automatically passed on to a higher level.

        def openFile(fileName)
        new FileInputStream(fileName)
        Now if I want to catch the exception here , I will write following code
        openFile("nonexistentfile" )
        println "Exception is here : " + ex

        I used catch(ex) without any type in front of the variable ex so I can catch just about any exception thrown my way. but this doesn’t catch Errors or Throwables other than Exceptions. To catch all of them, we will use catch(Throwable t).

      • JavaBeans

        here is Java class with getter and setter functions .

        public class Vehicle
        private int miles;
        private int year;
        public Vehicle(int theYear) { year = theYear; }
        public int getMiles() { return miles; }  //getter function for miles
        public void setMiles(int theMiles) { miles = theMiles; } //setter function for miles
        public int getYear() { return year; }
        public static void main(String[] args)
        Vehicle vehicle = new Vehicle(2008);
        System.out.println("Year: " + vehicle.getYear());
        System.out.println("Miles: " + vehicle.getMiles());
        System.out.println("Setting miles" );
        System.out.println("Miles: " + vehicle.getMiles());

        That’s all too familiar Java code, isn’t it? The output from the previous code is as follows:

        Year: 2008
        Miles: 0
        Setting miles
        Miles: 25

        You have to write getter and setter functions for the variables in Java . How you will feel if getter and setter function will be create internally , isn’t it will be good . Code will be less and will look more code . Groovy will do it for you

        class Vehicle
        def miles = 0
        final year
        year = theYear
        Vehicle vehicle = new Vehicle(2008)
        println "Year: $vehicle.year"
        println "Miles: $vehicle.miles"
        println 'Setting miles'
        vehicle.miles = 25
        println "Miles: $vehicle.miles"
        Output will be same
        Year: 2008
        Miles: 0
        Setting miles
        Miles: 25

        If you want a property to be read-only,then declare it final. This is not defining a final field but a read-only property—you can change the property from within instance methods of the defining class, but not from outside. Groovy provides a getter in this case and no setter .

        Groovy gives you the flexibility to initialize a JavaBean class. When constructing an object, simply give values for properties as comma-separated name-value pairs. This is a post construction operation if your class has a no-argument constructor. You can also design your methods so they can take named parameters. To take advantage of this feature, define the first parameter as a Map.

        Let’s see these in action:
        class Chair
        def type, height, width
        def access(location, weight, fragile)
        println "Received fragile? $fragile, weight: $weight, loc: $location"
        chair= new Chair(type: 'arm' , width: 10, height: 40)
        println "$chair.type, $chair.height, $chair.width"
        robot.access(50, x: 30, y: 20, z: 10, true)
        The output from the previous code is
        arm, 40, 10
        Received fragile? true, weight: 50, loc: ["x" :30, "y" :20, "z" :10]

        The instance of Chair took type, height, and width parameters as name-value pairs. In the call to the access( ) method, you set the first parameter, weight, to a single value, which is an Integer. You set the last parameter, fragile, to a single value as well. The rest of the parameters in the middle are name-value pairs for location.

        The example did not quite follow the same ordering as defined in the method definition .

        In Groovy If the number of parameters one send is more than the number of arguments the method expects and if the excess parameters are name-value pairs, then Groovy assumes the first argument of the method is a Map and groups all the name-value pairs together as values for the first parameter.

        Why not to use def all the time?

        Previous example can lead us to problem , such as when one pass three integer arguments. In this case, the arguments will be passed in order, no map is created from the arguments, and the result is not what he/she desire.

        one can avoid confusion like this by explicitly naming the first parameter as a Map, as shown here:

        def access(Map location, weight, fragile)
        print "Received fragile? $fragile, weight: $weight, loc: $location"

        Now, if your arguments do not contain two objects plus arbitrary name-value pairs, one will get an error.

        Now what if I have a method

        def user(name,age,profession){

        I called the function using (10,10,10) what will happen ? It will accept these variable . Though Groovy is optionally typed language we must be very careful while using it .

        why we should use valid name for variables ?

        Now if I call the function like

        chair= new Chair(type: '10’' , width: 10, height: 40)
        Since type is defined using def it will accept the value 10 .  

        The way I will prefer to write above code is

        class Chair
        String type
        float height
        float  width
        def access(Map location,float  weight,boolean fragile)
        println "Received fragile? $fragile, weight: $weight, loc: $location"

        Groovy also treats the trailing array parameter as optional. So, in the following example, you can send zero or more values for the last param- eter:

        def MyTask(name, String[] details)
        println "$name - $details"
        MyTask 'Call Me' , '123'
        MyTask 'Call Me' , '123' , '231'
        MyTask 'Check My Mail'

        The output from the previous code is as follows:

        Call Me- {"123" }
        Call Me- {"123" , "231" }
        Check My Mail - {}

        Providing mundane arguments to methods can get tiring. Optional parameters reduce noise and allow for sensible defaults.

      • Boolean Evaluation

        Groovy will automatically evaluate expressions as boolean.Java insists that you provide a boolean expression for the condition part of the if statement

        str = 'hello'
        if (str) { println 'hello' }
        Type Condition for truth
        Boolean true
        Collection not empty
        Characte r value not 0
        CharSequence length greater than 0
        Enumeration has more elements
        Iterator has text
        Number double value not 0
        Map not empty
        Matcher at least one match
        Object[ ] length greater than 0
        any other type reference not null


Tags: java , groovy

View All PostsLeave a Comment


comments powered by Disqus