Groovy - 数据类型



在任何编程语言中,您都需要使用各种变量来存储各种类型的信息。变量只不过是保留的内存位置以存储值。这意味着当您创建变量时,您会在内存中保留一些空间来存储与变量关联的值。

您可能希望存储各种数据类型的信息,例如字符串、字符、宽字符、整数、浮点数、布尔值等。根据变量的数据类型,操作系统分配内存并决定可以在保留的内存中存储什么。

内置数据类型

Groovy 提供了各种内置数据类型。以下是 Groovy 中定义的数据类型列表:

  • byte - 用于表示字节值。例如 2。

  • short - 用于表示短整型数。例如 10。

  • int - 用于表示整数。例如 1234。

  • long - 用于表示长整型数。例如 10000090。

  • float - 用于表示 32 位浮点数。例如 12.34。

  • double - 用于表示 64 位浮点数,是更长的十进制数表示形式,有时可能需要。例如 12.3456565。

  • char - 定义单个字符字面量。例如 'a'。

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

  • String - 这些是文本字面量,以字符串的形式表示。例如“Hello World”。

绑定值

下表显示了数值和十进制字面量的最大允许值。

byte -128 到 127
short -32,768 到 32,767
int -2,147,483,648 到 2,147,483,647
long -9,223,372,036,854,775,808 到 +9,223,372,036,854,775,807
float 1.40129846432481707e-45 到 3.40282346638528860e+38
double 4.94065645841246544e-324d 到 1.79769313486231570e+308d

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

Numeric 类

类型 除了基本类型外,还允许以下对象类型(有时称为包装类型):

  • java.lang.Byte
  • java.lang.Short
  • java.lang.Integer
  • java.lang.Long
  • java.lang.Float
  • java.lang.Double

此外,以下类可用于支持任意精度算术:

名称 描述 示例
java.math.BigInteger 不可变的任意精度带符号整数 30g
java.math.BigDecimal 不可变的任意精度带符号十进制数 3.5g

以下代码示例展示了如何使用不同的内置数据类型:

class Example { 
   static void main(String[] args) { 
      //Example of a int datatype 
      int x = 5; 
		
      //Example of a long datatype 
      long y = 100L; 
		
      //Example of a floating point datatype 
      float a = 10.56f; 
		
      //Example of a double datatype 
      double b = 10.5e40; 
		
      //Example of a BigInteger datatype 
      BigInteger bi = 30g; 
		
      //Example of a BigDecimal datatype 
      BigDecimal bd = 3.5g; 
		
      println(x); 
      println(y); 
      println(a); 
      println(b); 
      println(bi); 
      println(bd); 
   } 
}

当我们运行以上程序时,我们将得到以下结果:

5 
100 
10.56 
1.05E41 
30 
3.5
广告