一、java的数据类型分为【基本数据类型】和【引用数据类型】两类。
基本数据类型有8种:包括:
6种数字类型:byte、short、int、long、double、float
1种字符类型:char
1种布尔类型:boolean
对于 boolean所占用的字节,官方文档未明确定义,它依赖于 JVM 厂商的具体实现。逻辑上理解是占用 1 bit,但是实际中可能占1个字节/4个字节/...。会考虑计算机高效存储因素。
| 基本类型 | 字节 | 默认值 | |
| byte | 1(8位) | 0 | |
| short | 2 | 0 | |
| int | 4 | 0 | |
| long | 8 | 0L | |
| double | 8 | 0.0d | |
| float | 4 | 0.0f | |
| char | 2 | '\u0000' : 一个空格 | |
| boolean | 1 | false |
public class Test01 {
static char c;
static float f;
static double d;
static byte b;
static short sh;
static int i;
static long l;
static boolean bool;
public static void main(String[] args) {
System.out.println("char类型默认值"+c);
System.out.println("char类型默认值"+"\u0000");
System.out.println("float类型默认值:"+f);
System.out.println("double类型默认值:"+d);
System.out.println("byte类型默认值:"+b);
System.out.println("short类型默认值:"+sh);
System.out.println("int类型默认值:"+i);
System.out.println("long类型默认值:"+l);
System.out.println("boolean类型默认值:"+bool);
}
}

这里的char类型的默认值是'\u0000' ,指代的是一个空格。
\u开头的是一个Unicode码的字符,每一个'\u0000'都代表了一个空格。
引用数据类型有3种:类、接口、数组。
String是一个类,所以它是引用数据类型。java.lang.String
二、基本数据类型之间的转换
高字节-->低字节,会造成精度的缺失。所以需要进行强制类型转换。
低字节-->高字节,不会造成精度的缺失,所以不需要进行强制类型转换。
public class Test02 {
public static void main(String[] args) {
int a = 10;
short b = (short) a;
short c = 100;
int d = c;
}
}
三、包装类型
每一个基本数据类型都有对应的包装类型。
包装类型就是每一个基本数据类型对应的对象。使用包装类可以将基本数据类型当作对象来使用。
| 基本类型 | 包装类 |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| double | Double |
| float | Float |
| char | Character |
| boolean | Boolean |
public class Test03 {
public static void main(String[] args) {
//装箱
Integer a = 20;
//拆箱
int b = a;
//装箱:基本数据类型变为包装类型
//拆箱:包装类型拆为基本数据类型
Integer n1 = new Integer(10);
Integer n3 = 10; //等价于Integer 那=Integer.valueOf(10)。n3使用的是常量池中的对象
int n2 = 10;
//Integer = int :先拆箱,后比较
System.out.println(n1==n2);//true
System.out.println(n1==n3);//false
}
}
四、常见面试题


被折叠的 条评论
为什么被折叠?



