目录

Groovy - 变量

Groovy中的变量可以通过两种方式定义 - 使用数据类型的native syntax ,或者by using the def keyword 。 对于变量定义,必须明确提供类型名称或替换使用“def”。 这是Groovy解析器所必需的。

Groovy中有以下基本类型的变量,如前一章所述 -

  • byte - 用于表示字节值。 一个例子是2。

  • short - 用于表示短数字。 一个例子是10。

  • int - 用于表示整数。 一个例子是1234。

  • long - 用于表示长数字。 一个例子是10000090。

  • float - 用于表示32位浮点数。 一个例子是12.34。

  • double - 用于表示64位浮点数,这些浮点数是较长的十进制数表示,有时可能需要这些数字。 一个例子是12.3456565。

  • char - 这定义了单个字符文字。 一个例子是'a'。

  • Boolean - 这表示一个布尔值,可以是true或false。

  • String - 这些是以String the form表示的文本文字。 例如“Hello World”。

Groovy还允许其他类型的变量,如数组,结构和类,我们将在后续章节中看到。

变量声明

变量声明告诉编译器为变量创建存储的位置和数量。

以下是变量声明的示例 -

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

命名变量 (Naming Variables)

变量的名称可以由字母,数字和下划线字符组成。 它必须以字母或下划线开头。 大写和小写字母是不同的,因为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 

我们可以看到xX是两个不同的变量,因为区分大小写,在第三种情况下,我们可以看到_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 
↑回到顶部↑
WIKI教程 @2018