Basic Groovy Syntax

The syntax of the Groovy language is derived from Java, but is enhanced with specific constructs for Groovy, and allows certain simplifications. Groovy allows you to leave out some elements of syntax like package prefix, parentheses, and semicolon which brings the code to the bare minimum. 

On this page:

Comments in Groovy

Groovy supports single and multi-line comments. Single line comments start with // and can be found at any position in the line. Multi-line comments start with /* and */

//This is a single line comment in Groovy
/* This is a multi-line comment in Groovy
that starts in the first line and 
ends here */

Identifiers

Identifiers are used to define variables, functions or other user defined variables. Identifiers start with a letter, a dollar or an underscore. They cannot start with a number. Here are some examples of valid identifiers:

def employeeName 
def student1 
def student_name

Keywords

While writing your scripts make sure you do not use the existing keywords of the Groovy language like break, package etc to name your variables or constants. See here for the list of keywords.

String Concatenation

The Groovy strings can be concatenated with a + operator.

"a" + "b"
//returns ab

You can use the backslash character \ to escape the quotes

"\"a\"" + "b"
//returns "a"b

Semicolons

Semicolons are used to separate statements, but they are optional in Groovy as long as you write one statement per line. If you use multiple statements on the same line you can either use a semicolon or a newline to separate the statements.

def A = "a" + "b"; def B = "c" + "d" // You need a semi-colon to separate the two statements on the same line

//You can instead add a new line to separate the statements in Groovy
def A = "a" + "b"
def B = "c" + "d

Return statement

The last line of a method in Groovy is automatically considered as the return statement. For this reason, an explicit return statement can be left out. To return a value that is not on the last line, the return statement has to be declared explicitly.

def a = 3 + 2 //returns 5. A return statement can be omitted

Next: Program structure in Groovy >>