Java 基本数据类型
Java 基本数据类型包括以下 8 种:
类型 | 名称 | 长度 (bits) | 范围 |
---|---|---|---|
byte | 字节 | 8 | -128 ~ 127 |
short | 短整型 | 16 | -32768 ~ 32767 |
int | 整型 | 32 | -2147483648 ~ 2147483647 |
long | 长整型 | 64 | -9223372036854775808 ~ 9223372036854775807 |
float | 单精度浮点型 | 32 | -3.4x10^38 ~ 3.4x10^38 |
double | 双精度浮点型 | 64 | -1.7x10^308 ~ 1.7x10^308 |
char | 字符型 | 16 | Unicode 编码 |
boolean | 布尔型 | 1 | true / false |
使用方式
下面是使用方式示例:
public class Main {
public static void main(String[] args) {
// 声明 byte 类型变量
byte b = 100;
System.out.println("Byte 范围:" + Byte.MIN_VALUE + " ~ " + Byte.MAX_VALUE);
System.out.println("b 的值:" + b);
// 声明 short 类型变量
short s = 10000;
System.out.println("Short 范围:" + Short.MIN_VALUE + " ~ " + Short.MAX_VALUE);
System.out.println("s 的值:" + s);
// 声明 int 类型变量
int i = 100000;
System.out.println("Integer 范围:" + Integer.MIN_VALUE + " ~ " + Integer.MAX_VALUE);
System.out.println("i 的值:" + i);
// 声明 long 类型变量
long l = 10000000;
System.out.println("Long 范围:" + Long.MIN_VALUE + " ~ " + Long.MAX_VALUE);
System.out.println("l 的值:" + l);
// 声明 float 类型变量
float f = 234.5f;
System.out.println("Float 范围:" + Float.MIN_VALUE + " ~ " + Float.MAX_VALUE);
System.out.println("f 的值:" + f);
// 声明 double 类型变量
double d = 123.4;
System.out.println("Double 范围:" + Double.MIN_VALUE + " ~ " + Double.MAX_VALUE);
System.out.println("d 的值:" + d);
// 声明 char 类型变量
char c = 'A';
System.out.println("c 的值:" + c);
// 声明 boolean 类型变量
boolean bool = true;
System.out.println("bool 的值:" + bool);
}
}
练习题
- 声明一个名为 age 的 int 类型变量,并将其初始值设为你的年龄。
- 声明一个名为 price 的 float 类型变量,并将其初始值设为你喜欢的物品的价格。
- 声明一个名为 name 的 String 类型变量,并将其初始值设为你的名字。
- 声明一个名为 isValid 的 boolean 类型变量,并将其初始值设为你是否有效的。
- 声明一个名为 initial 的 char 类型变量,并将其初始值设为你的名字的首字母。
- 声明一个名为 score 的 double 类型变量,并将其初始值设为你的考试得分。
int age = 18;
float price = 99.99f;
String name = "John Doe";
boolean isValid = true;
char initial = 'J';
double score = 95.5;