八种数据类型
- 字节(Byte):计算机文件大小的基本单位。Bit意为“位”、“比特”,是计算机运算的基础;二进制中的一位,是二进制最小信息单位。
1字节(Byte)=8位(Bit)
2字节(Byte)=16位(Bit)
4字节(Byte)=32位(Bit)
8字节(Byte)=64位(Bit)
说明:在内存计算过程中,字节少的数据运算速度更快;在硬盘存储中,字节少的数据类型也可以充分存入更多数据。
- 单位换算
1字节(Byte)=8位(Bit)
1KB=1024byte
1MB=1024KB
1GB=1024MB
1TB=1024GB
1PB=1028TB
数据类型 | 关键字 | 占用字节 | 取值范围 | 默认值 |
布尔型 | boolean | 不定值 | true、false | false |
字节型 | byte | 1 | -128~127 | 0 |
短整型 | short | 2 | -32768~32767 | 0 |
整型 | int | 4 | -2147483648~2147483647 | 0 |
长整型 | long | 8 | -9223372036854775808~9223372036854775807 | 0 |
字符型 | char | 2 | 0~65535 | '\u0000' |
单精度浮点型 | float | 4 | 1.4E-45~3.4028125E38 | 0.0F |
双精度浮点型 | double | 8 | 4.9E-324~1.7976931348623157E308 | 0.0D |
public class Test{
public static void main(String[] args){
int num = 10; //局部变量
//八种数据类型
//数值类型
byte b = 10; //占用1个字节,取值范围:-128~127
short s = 10; //占用2个字节,取值范围:-32768~32767,实际开发中使用较少
int i = 10; //占用4个字节
long lon = 100L; //占用8个字节
float f = 10.98F; //占用4个字节
double d = 10.12456D; //占用8个字节
char c = 'A'; //占用2个字节,取值范围:0~65535
char c1 = 97; // ASCII码表,97 ==> a
boolean bool = true; //占用字节不确定
//定义变量的格式:类型 变量名 ==> 声明一个变
b = 20; //赋值
System.out.println(c1);
System.out.println(num);
System.out.println(d);
System.out.println(f);
}
}
基本数据类型的转换
自动类型转换:
容量小的类型自动转换成容量大的数据类型;
byte、short、int它们三者在计算时会自动转换成int类型
int值转换为float值,或者long转换成double值,不需要强制转换,但可能都丢失精度。
public class Test1{
public static void main(String[] args){
byte b = 10;
short s = b; //把一个字节赋值给一个短整型,自动转换
int i = s; //把一个短整型复制给一个整型变量,自动转换
long lon = i; //自动转换
float f = 20.1F;
double d = f;
//char -> int 可自动转换
char c = 'A';
int c1 = c;
//float 和 double 是属于近似值
//byte、char、int、long 是属于精确值
//精确值转近似值时可能丢失精度
int num = 2076435466;
float num2 = num; //运行后的值是2.07643546E9(2076435460),比实际数值小
//面试题:byte、short、int在计算时会自动转为int类型
short s1 = 10;
//s1 = s1 + 1; //错误: 不兼容的类型: 从int转换到short可能会有损失
int s2 = s1 + 1;
//把容量大的类型转换成容量小的数据类型时,需要加上强制转换符
//有可能造成精度降低或数据溢出,使用时要小心。
//boolean类型不能转换成任何其他数据类型
s1 = (short)(s1 + 1); //强制类型转换符
long n = 100L;
int i1 = (int)n;
System.out.println(i1);
}
}