一、变量声明
问:变量声明是什么?
答:告诉编译器为变量创建存储的位置和大小。
class Example {
static void main(String[] args) {
// x is defined as a variable
String x = "Hello";
// The value of the variable is printed to the console
println(x);
}
}
运行结果如下:
Hello
二、 变量命名
变量的名称可以由字母、数字和下划线字符组成,必须以字母或下划线开头。
大写和小写字母是不同的,因为Groovy就像Java一样,是一种区分大小写的编程语言。
class Example {
static void main(String[] args) {
// Defining a variable in lowercase
int x = 5;
// Defining a variable in uppercase
int X = 6;
// Defining a variable with the underscore in it's name
def _Name = "Joe";
println(x);
println(X);
println(_Name);
}
}
运行结果如下:
5
6
Joe
注意:x和X是两个不同的变量,因为区分大小写,在第三种情况下,_Name以下划线开头。
三、打印变量
可以使用println函数打印变量的当前值。
class Example {
static void main(String[] args) {
//Initializing 2 variables
int x = 5;
int X = 6;
//Printing the value of the variables to the console
println("The value of x is " + x + "The value of X is " + X);
}
}
运行结果如下:
The value of x is 5 The value of X is 6