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:
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 */
Code Block |
---|
language | groovy |
---|
linenumbers | true |
---|
|
//This is a single line comment in Groovy |
Code Block |
---|
language | groovy |
---|
linenumbers | true |
---|
|
/* 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:
Code Block |
---|
language | groovy |
---|
linenumbers | true |
---|
|
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.
Code Block |
---|
language | groovy |
---|
linenumbers | true |
---|
|
"a" + "b"
//returns ab |
You can use the backslash character \ to escape the quotes
Code Block |
---|
language | groovy |
---|
linenumbers | true |
---|
|
"\"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.
Code Block |
---|
language | groovy |
---|
linenumbers | true |
---|
|
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.
Code Block |
---|
language | groovy |
---|
linenumbers | true |
---|
|
def a = 3 + 2 //returns 5. A return statement can be omitted |
...
Include Page |
---|
| JMWE:Basic Groovy Syntax |
---|
| JMWE:Basic Groovy Syntax |
---|
|