JAVA中的包装类

转自:https://www.imooc.com/code/2249

仅做个人学习记录之用,侵删。

 

相信各位小伙伴们对基本数据类型都非常熟悉,例如 int、float、double、boolean、char 等。基本数据类型是不具备对象的特性的,比如基本类型不能调用方法、功能简单。。。,为了让基本数据类型也具备对象的特性, Java 为每个基本数据类型都提供了一个包装类,这样我们就可以像操作对象那样来操作基本数据类型。 

基本类型和包装类之间的对应关系:

包装类主要提供了两大类方法:

1. 将本类型和其他基本类型进行转换的方法

2. 将字符串和本类型及包装类互相转换的方法

我们以 Integer 包装类为例,来看下包装类的特性。

Integer 包装类的构造方法:

如下代码所示:

Integer包装类的常用方法:

编辑器中列举了 Integer 类型和基本数据类型之间的转换,结合运行结果先认识一下吧!

public class HelloWorld {
    public static void main(String[] args) {
        
		// 定义int类型变量,值为86
		int score1 = 86; 
        
		// 创建Integer包装类对象,表示变量score1的值
		Integer score2=new Integer(score1);
        
		// 将Integer包装类转换为double类型
		double score3=score2.doubleValue();
        
		// 将Integer包装类转换为float类型
		float score4=score2.floatValue();
        
		// 将Integer包装类转换为int类型
		int score5 =score2.intValue();

		System.out.println("Integer包装类:" + score2);
		System.out.println("double类型:" + score3);
		System.out.println("float类型:" + score4);
		System.out.println("int类型:" + score5);
	}
}

  运行结果:

Integer包装类:86
double类型:86.0
float类型:86.0
int类型:86
posted @ 2020-02-06 16:38  风铃如沧海  阅读(197)  评论(0编辑  收藏  举报