为了了解Groovy的基本语法,让我们先看看一个简单的Hello World程序。
1、创建Hello World程序
(1)在IntelliJ IDEA中,选择New-Groovy Class。
(2)创建Hello World程序,你只要输入以下几行简单的代码就可实现。
class HelloWorld {
static void main(String[] args){
println('Hello World');
}
}
当我们运行上面的程序,我们会得到以下结果:
Hello World
2、在Groovy中导入语句
import语句可以用来导入,可以再你的代码中使用其他库的功能,这里通过使用Import关键字来完成。
下面演示了如何使用MarkupBuilder的类,它可能是最常用的创建HTML或XML标记的类之一。
注:需要依赖一下信息:
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-xml</artifactId>
<version>2.5.4</version>
</dependency>
import groovy.xml.MarkupBuilder
def xml = new MarkupBuilder()
默认情况下,Groovy在代码中包括以下库,因此您不需要显式导入它们。
import java.lang.*
import java.util.*
import java.io.*
import java.net.*
import groovy.lang.*
import groovy.util.*
import java.math.BigInteger
import java.math.BigDecimal
3、Groovy令牌
令牌可以是一个关键字,一个标识符,常量,字符串文字或符号。
println('Hello World');
在上面的代码行中,有两个令牌,首先是关键词的println而接下来就是字符串的“Hello World”。
4、Groovy评论
在您的代码中使用注释,Groovy的注释可以是单行或多行。
单行注释使用“//”,在该行的任何位置来识别。
一个例子如下:
class Example {
static void main(String[] args) {
// Using a simple println statement to print output to the console
println('Hello World');
}
}
多行注释标识与在开始/ *和* /识别多行注释的末尾。
一个例子如下:
class Example {
static void main(String[] args) {
/* This program is the first program
This program shows how to display hello world */
println('Hello World');
}
}
5、分号
Groovy定义多个语句之间的区别使用分号,类似Java编程语言。
一个例子如下:例子显示出了分号使用了不同行的代码语句之间进行区分。
class Example {
static void main(String[] args) {
// One can see the use of a semi-colon after each statement
def x = 5;
println('Hello World');
}
}
6、身份标识
标识符被用来定义变量,函数或其他用户定义的变量。标识符以字母开头,美元或下划线。他们不能以数字开头。以下是有效标识符的一些例子。
def employeename
def student1
def student_name
其中,def是在Groovy用来定义标识符的关键字。
下面是一个如何在我们的Hello World陈翔中使用标识符代码示例。
class HelloWorld {
static void main(String[] args){
// One can see the use of a semi-colon after each statement
def x = 5;
println('Hello World');
}
}
在上述的例子中,变量x被用作标识符。
7、关键词
关键字作为名称建议是在Groovy编程语言中保留的特殊字。 下表列出了在Groovy中定义的关键字。
as | assert | break | case |
catch | class | const | continue |
def | default | do | else |
enum | extends | false | Finally |
for | goto | if | implements |
import | in | instanceof | interface |
new | pull | package | return |
super | switch | this | throw |
throws | trait | true | try |
while |
8、空白
空白是在编程语言如Java和Groovy用来形容空格,制表符,换行符和注释术语。空格分隔从另一个声明的一部分,使编译器,其中一个元素标识的声明。
例如,在下面的代码示例,存在关键字def和变量x之间的空白。这是为了让编译器知道DEF是需要被使用,并且是x应该是需要被定义的变量名的关键字。
def x = 5;
9、文字
文字是在groovy中表示固定值的符号。Groovy语言有符号整数,浮点数,字符和字符串。
下面是一些在Groovy编程语言文字的例子。
12
1.45
'a'
"aa"