Java的基本类型分为整型(byte、short、int、long)、浮点型(float、double)、字符型(char)和布尔型(boolean)4种。
每一种基本类型都对应有一个封装类,方便涉及类和对象的操作。基本类型与对应封装类对象的相互转换:
装箱:将基本类型的变量转换成对应引用类型的变量。
拆箱:将引用类型的变量转换成对应基本类型的变量。
整型
整型变量用于表示带符号的整数。可以使用十进制、十六进制(以“0X”或“0x”开头)和八进制(以“0”开头)赋值。分为4种:
byte:表示8位二进制带符号整数。
范围:-27~27-1
默认值:0
封装类:java.lang.Byte
short:表示16位二进制带符号整数。
范围:-215~215-1
默认值:0
封装类:java.lang.Short
int:表示32位二进制带符号整数。
范围:-231~231-1
默认值:0
封装类:java.lang.Integer
long:表示64位二进制带符号整数。赋值需要以“L”或“l”结尾。
范围:-263~263-1
默认值:0
封装类:java.lang.Long
浮点型
浮点型变量用于表示带符号的浮点数,浮点数通过四舍五入处理超出有效位数的小数部分。浮点数后加上“F”或“f”表示单精度浮点数,不加或者加上“D”或“d”表示双精度浮点数。分为2种:
float:表示32位二进制单精度浮点数。
符号位:1
指数位:8
尾数位:23
有效位数:8
绝对值范围:1.4e-45f~3.4028235e+38f
默认值:0.0f
封装类:java.lang.Float
double:表示64位二进制双精度浮点数。
符号位:1
指数位:11
尾数位:52
有效位数:16
绝对值范围:4.9e-324~1.7976931348623157e+308
默认值:0.0
封装类:java.lang.Double
字符型
字符型变量用于表示Unicode字符。字符型变量赋值有两种方式,一种是使用单引号将单个字符括起来,另一种是直接赋无符号整数。
char:表示16位无符号整数。只存储单个字符。
范围:0~216-1
默认值:0
封装类:java.lang.Character
布尔型
布尔型变量可取逻辑真和逻辑假两种值。布尔型变量不能与0和1对等。
boolean:表示一个判断的逻辑结果。
取值:true(逻辑真)、false(逻辑假)
默认值:false
封装类:java.lang.Boolean
测试
如果在方法中定义变量,使用时需要为变量赋初值。为了查看默认值,把所有变量都定义为成员变量。
byte
1 byte b;
2 @Test
3 void testByte() {
4 System.out.print("byte: " +
b);
5 b = 10
;
6 System.out.println(" -> " +
b);
7 System.out.println("取值范围:[ " + Byte.MIN_VALUE + ", " + Byte.MAX_VALUE + " ]"
);
8 }
testByte
输出结果:
short
1 short s;
2 @Test
3 void testShort() {
4 System.out.print("short: " +
s);
5 s = 200
;
6 System.out.println(" -> " +
s);
7 System.out.println("取值范围:[ " + Short.MIN_VALUE + ", " + Short.MAX_VALUE + " ]"
);
8 }
testShort
输出结果:
int
1 int i;
2 @Test
3 void testInt() {
4 System.out.print("int: " +
i);
5 i = 40000
;
6 System.out.println(" -> " +
i);
7 System.out.println("取值范围:[ " + Integer.MIN_VALUE + ", " + Integer.MAX_VALUE + " ]"
);
8 }
testInt
输出结果:
long
1 long l;
2 @Test
3 void testLong() {
4 System.out.print("long: " +
l);
5 l = 8000000000l
;
6 System.out.println(" -> " +
l);
7 System.out.println("取值范围:[ " + Long.MIN_VALUE + ", " + Long.MAX_VALUE + " ]"
);
8 }
testLong
输出结果:
float
1 float f;
2 @Test
3 void testFloat() {
4 System.out.print("float: " +
f);
5 f = 0.123456789f;
// 超出8位有效数字
6 System.out.println(" -> " +
f);
7 System.out.println("绝对值范围:[ " + Float.MIN_VALUE + ", " + Float.MAX_VALUE + " ]"
);
8 }
testFloat
输出结果:
double
1 double d;
2 @Test
3 void testDouble() {
4 System.out.print("double: " +
d);
5 d = 0.12345678123456789;
// 超出16位有效数字
6 System.out.println(" -> " +
d);
7 System.out.println("绝对值范围:[ " + Double.MIN_VALUE + ", " + Double.MAX_VALUE + " ]"
);
8 }
testDouble
输出结果:
char
1 char c;
2 @Test
3 void testChar() {
4 System.out.print("char: " + (
int) c);
// 0对应的Unicode字符为非打印字符,故转成int型
5 c = '符'
;
6 System.out.print(" -> " +
c);
7 c = 31526
;
8 System.out.println(" -> " +
c);
9 }
testChar
输出结果:
boolean
1 boolean bool;
2 @Test
3 void testBoolean() {
4 System.out.print("boolean: " +
bool);
5 bool =
true;
6 System.out.println(" -> " +
bool);
7 }
testBoolean
输出结果:
转载于:https://www.cnblogs.com/lqkStudy/p/10966234.html