Skip to main content

Posts

Showing posts with the label Groovy

Java Vs Groovy - Enum Demo

 Java 5 introduced enum that solve the problem with enumeration. Groovy also support that feature, as shown here.  Enum example using Java. enum ShirtSize { SMALL,MEDIUM,LARGE,EXTRALARGE } class ShirtImplementation { public void orderShirt(ShirtSize size) { switch(size) { case SMALL : System.out.println("The size of the shirt is small"); break; case MEDIUM : System.out.println("The size of the shirt is medium"); break; case LARGE : System.out.println("The size of the shirt is large"); break; case EXTRALARGE : System.out.println("The size of the shirt is extra large"); break; default : System.out.println("The shirt size is not available"); break; } } } public class EnumExample { public static void main(String args[]) { ShirtImplementation shirtImplementation = new ShirtImplementation(); shirtImplementation.orderShirt(ShirtSize.SMALL); shirtImplementation.o...

Groovy vs Java - varars demo

 Java 5 varargs feature allows you to pass a variable number of arguments to methods. Groovy also support this feature, See the below example.  Java way for implementing varargs. public class VarargsDemo { public static void main(String[] args) { int[] numbers = {10,20,30,40,50}; System.out.println("Total is " + VarargsDemo.calculateTotal(numbers)); } public static int calculateTotal(int... numbers) { int total = 0; for(int number : numbers) { total += number; } return total; } }  Groovier way for implementing varargs. def calculateTotal(int... numbers) { def total = 0 for(number in numbers) { total += number } total } println calculateTotal(10,20,30,40,50)

Groovy vs Java - For-Each loop

 The latest version of Java (version 1.5 and later) have for-each loop support. Groovy have many type of powerful loops as well as it support traditional Java loops.  This is very simple example for for-each loop.  Java way for implementing for-each loop public class ForEachLoopDemo { public static void main(String[] args) { String[] countryLists = {"India","US","UK"}; for(String country : countryLists) { System.out.println(country); } } }  Groovier way for implementing for-each loop for(country in countryList) { println country }

Groovy vs Java - Autoboxing

 By default Groovy have autoboxing feature because of its dynamic nature. By default Groovy treats all the primitive types as objects, for example Integer for int, Float for float etc. See the below example. int integerVariable = 10; println integerVariable.class.name float floatVariable = 0.5f println floatVariable.class.name char charVariable = 'c' println charVariable.class.name double doubleVariable = 1.5d println doubleVariable.class.name boolean boolVariable = true println boolVariable.class.name  Here I have created the some variable for primitive types and print the corresponding class name. This result would be, java.lang.Integer java.lang.Float java.lang.Character java.lang.Double java.lang.Boolean   In Java, auto boxing and unboxing involve constant casting. But Groovy automatically treats all the primitive types variable as Object. That's why the print statement prints the corresponding class name for primitive types.

Groovy Vs Java - Exception Handling

 Some times java forces you to handle checked exception. Consider simple case: If you want to create object for FileInputStream, Java forces you to catch "FileNotFoundException".  For catching this exception almost every developers use  empty catch block. That's why normal Java application have lot of empty catch blocks like this. import java.io.FileInputStream; import java.io.FileNotFoundException; public class ExceptionHandling { public static void main(String[] args) { try { FileInputStream fin = new FileInputStream("D://sample.txt"); } catch (FileNotFoundException e) { } } }  But Groovy does not force you handle the exception.  If any exception you don't handle is automatically passed on to a higher level. Groovier way for above example def openFile() { //Here the exception is automatically redirected to caller method. new FileInputStream("D://sample.txt") } try{ openFile() } catch(FileNotFoundException e) { prin...

Groovy - Opening system applications

 In Java we have exec() method for opening system applications. In groovy this is more easier than Java. This is groovier way for opening notepad application. "notepad.exe".execute()  When you called the execute() method on String object, Groovy created the instance that extends java.lang.Process ,  just like exec() method of RunTime did in the Java code.   You can verify this by using following code. println "notepad.exe".execute().class.name  This will print " java.lang.Process "

Data types in Java and Groovy

All the java people know, Java have two different kind of data types for storing data, those are    1. Primitive types (such as int,float,char, and boolean)    2. Reference types (such as String and Object) The disadvantages of primitive types.   1. You cannot call methods, an values of primitive types . See the example,      int a = 10;      a.toSting();   If you do like this, while compilation time, the JVM will give the following error.     "You cannot invoke on toString() on primitivt type int"   To overcome this issue, the java developers needs Wrapper classes, such as Integer for int, Float for float, and etc.., See the below example    Integer a= new Integer(10);    a.toString(); But In Groovy we don't have these kind of headache, because it treats everything as an object. I am going to add two integer arraylist values using both Groovy and Java, then se...

Method parameters in Groovy

  Groovy allows you to create a methods with optional parameter, but the trailing parameter is only optional, see the below example. class MathLog { def log(x,base=10) { Math.log(x)/Math.log(base) } }  Here the base is optional parameter. The main method. MathLog mathLog = new MathLog() println mathLog.log(10) println mathLog.log(10,2)  The function call   mathLog.log(10)  takes the base value as 10, that's defined in the method itself but the function call mathLog.log(10,2)  takes the 2 as a base value. The output is 1.0 3.3219280948873626 Note:   In Groovy the return statement is optional , because by default it's return the last line output to calling method.

Java bean vs Groovy bean

Java Beans.    Generally the java bean class have a lot of variables and accessor(setter and getter) methods. The developer needs to write a setter and getter method for those variable as well as the developer explicitly needs to tell that variables and accessor methods are public. See the below example. //The Country.java bean public class Country {     public String name;     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     } //The java main class public class JavaBeanDemo {     public static void main(String[] args) {         Country country = new Country();         country.setName("India");         System.out.print(countr...

Safe navigation operator in Groovy

 The Safe navigation operator(?.) is used for eliminating "Null" check in Groovy. See the below example.  In java the null value check is like this.    String str = null;    if(str !=null) {       System.out.println(str.reverse());    } Same thing in Groovy. class SafeNavigationOperatorDemo {     public static void main(String[] args) {         def str = null;         println str ?. reverse()         str = "Cool stufs...."         println str ?. reverse()     } } This will print the message like this. null ....sfuts looC

Loops in Groovy

  The Groovy loops are very powerful and easy to use compared to Java. Here I printed 0 to10 integer values using both Java and Groovy language. The java code. public class LoopsInJava {     public static void main(String[] args) {         for(int i=0;i<10;i++) {             System.out.println(i);         }     } } The Groovy code. class LoopsInGroovy {     public static void main(String[] args) {         10.times {             println it         }     } } Just notify the real power of Groovy now. If suppose you want to print some even numbers that are in between 2 to 20 then, you can able do like this. 2.step(20,2) {     println it } It is equivalent to for(int i=2;i...

Hello world application in groovy

   Hi everyone, I am going to play with Groovy language. The dynamic behaviour is one of the key feature of this language and it also object oriented language that runs on the JVM. It include the some of the major features that are available in some other languages like Ruby, Python, and Smalltalk. The Groovy automatically include the groovy.lang.*, groovy.util.*, java.lang.*, java.util.*, java.io.*, java.net.*, java.math.BigInteger and BigDecimal packages into our application.  As usual I started with my "Hello world" aplication. class HelloWorld {     public static void main(String[] args) {         println "Hello World"     } }