目录
- 八大基本数据类型
- 自动装箱和自动拆箱机制
- 整数型常量池
- 为什么需要基本数据类型
- 为什么引入包装数据类型
八大基本数据类型
基本数据类型包含:byte、int、long、short、double、float、boolean、char,八种基本数据类型。
数据类型 | 默认值 |
---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | ‘u0000’ |
String (or any object) | null |
boolean | false |
Java是一门静态类型的编程语言,必须先申明变量,才能使用。
自动装箱和自动拆箱机制
他们都有对应的包装数据类型,他们分别是
基本数据类型 | 包装数据类型 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package Integer; /* 关于Integer类的构造方法,有两个: Integer(int) Integer(String) */ public class Test { public static void main(String[] args) { //将数字100转换为Integer类型 Integer x = new Integer(100); System.out.println(x); //将字符串123转换为Integer类型 Integer y = new Integer("123"); System.out.println(y); Double d = new Double(1.23); System.out.println(d); Double e = new Double(1); System.out.println(e); }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12package Integer; /* 在JDK1.5之后支持自动拆箱和自动装箱 */ public class Test { public static void main(String[] args) { Integer x = 100;//自动装箱 int类型自动转换为Integer int y = x;//自动拆箱 Integer自动转换为int } }
整数型常量池
java中为了提高程序执行效率,将-128-127之间的所有包装对象提前创建好,放到方法区整数型常量池当中,目的是只要用这个区间数据不需要在new,直接从整数型常量池中取出。
为什么需要基本数据类型
Java为八大基本数据类型都提供了包装类,但是基本数据类型还是必不可少,这是因为再Java中创建对象是一件代价较大的事情,而且基本数据类型的使用十分广泛。不舍弃基本数据类型是为了提高Java的执行效率。
为什么引入包装数据类型
- Java是一中面向对象的语言,而基本数据类型不具备面向对象的特征。
- 包装数据类型中包含了许多方法,比如max和min等。
最后
以上就是隐形枫叶最近收集整理的关于Java基本数据类型和包装数据类型的区别的全部内容,更多相关Java基本数据类型和包装数据类型内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复