Category Archives: Tutorials

Groovy language guidelines for Java Developers

The simple guidlines for java developers who are starting to learn Groovy programming language.

Semicolons:

In Groovy, the semicolons after every statement line of code is optional.

If you’re copying over your java code into a Groovy program, then you may want to remove them to make it consistant and code to look nicer.

println "Hey CodeDairy, I'm on Groovy. No more semicolons on this line"

return value:

return keywords in a method to return a value is optional in groovy and it’s good in the smaller lines of code in a method like below.

Example :

//when the lines of code is small

def discountCode(amt){
if ( amt > 500 ) {
"GRAND"
}else {
"TENOFF"
}
}

data types: def or types OR def and type?:

Either you use def or actual data type. Using the both the keywords are redundant. As we all know, in Groovy the type def is actually an Object. We can assign any value to it.

For example

def Integer purchaseAmt = 5876 // The data type is not required.

Parentheses is optional:

You may have already seen the Hello world println statements like below >

//Groovy, printing hello world

println "Hello, World !"

one more example

//Groovy, output values of var1, var2
println var1, var2

No Getters and Setters required:

In Groovy, the getters and setters methods need not be generated like we do in java becuase the Groovy compiler bydefault does it for us.

Let’s see how this is done in Java and Groovy

Java:

class Book {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
Groovy:

//No getters and setters required

class Book {
String name;
}

Tripple codes for Multiline strings:

You could use the “”” ( Three double quotes) for the multilines for example

print """This is a Groovy Multiline Strings
Tests
That is nice """

instead doing like below in java

println("This is a Groovy Multiline strings "+
"Tests" +
"That is nice");

Hope you enjoyed reading this. Please post the comments, suggests below. Thank you


How does Groovy helps Lazy coders

Groovy helps lazy developers

Groovy programming language

Groovy

The below list of things that developers need not worry about in Groovy programming language.

  • No need to put semicolon in the code after every statement
  • No modifiers
  • No need to define classes
  • No need to define variable types ( Groovy is Java code without types )
  • No need to compile as it interprets source code directly
  • Developers first line of code “Hello World” is simple to write in Groovy without creating a file.
 cmd>groovy -e "println 'Hello World!'"

All together Groovy means less typing….