在 Java 中,数字有几种不同的数据类型,每种类型的存储容量和精度各不相同。主要分为整数类型和浮点类型。以下是这些数据类型的详细介绍:
整数类型
-
byte
- 大小: 1 字节 (8 位)
- 取值范围: -128 到 127
- 示例:
byte b = 100;
-
short
- 大小: 2 字节 (16 位)
- 取值范围: -32,768 到 32,767
- 示例:
short s = 10000;
-
int
- 大小: 4 字节 (32 位)
- 取值范围: -2^31 到 2^31-1 (-2,147,483,648 到 2,147,483,647)
- 示例:
int i = 100000;
-
long
- 大小: 8 字节 (64 位)
- 取值范围: -2^63 到 2^63-1 (-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807)
- 示例:
long l = 100000L;
浮点类型
-
float
- 大小: 4 字节 (32 位)
- 取值范围: 约 ±3.40282347E+38F (6-7 位小数)
- 示例:
float f = 234.5f;
-
double
- 大小: 8 字节 (64 位)
- 取值范围: 约 ±1.79769313486231570E+308 (15 位小数)
- 示例:
double d = 123.4;
大数字类型 (Java 中的大数字类)
除了上述基本数据类型外,Java 还提供了 BigInteger
和 BigDecimal
类,用于处理非常大的整数和浮点数,且这些类位于 java.math
包中。
-
BigInteger
- 用于表示任意精度的整数。
- 示例:
import java.math.BigInteger; BigInteger bigInt = new BigInteger("123456789012345678901234567890");
-
BigDecimal
- 用于表示任意精度的浮点数。
- 示例:
import java.math.BigDecimal; BigDecimal bigDec = new BigDecimal("12345.6789012345678901234567890");
示例代码
以下是使用各种数字数据类型的示例代码:
public class NumericTypesExample {
public static void main(String[] args) {
// 整数类型
byte byteVal = 100;
short shortVal = 10000;
int intVal = 100000;
long longVal = 100000L;
// 浮点类型
float floatVal = 234.5f;
double doubleVal = 123.4;
// 大数字类型
BigInteger bigIntVal = new BigInteger("123456789012345678901234567890");
BigDecimal bigDecVal = new BigDecimal("12345.6789012345678901234567890");
// 输出各个数值
System.out.println("byte value: " + byteVal);
System.out.println("short value: " + shortVal);
System.out.println("int value: " + intVal);
System.out.println("long value: " + longVal);
System.out.println("float value: " + floatVal);
System.out.println("double value: " + doubleVal);
System.out.println("BigInteger value: " + bigIntVal);
System.out.println("BigDecimal value: " + bigDecVal);
}
}