41 包装类

包装类

  1. java提供了8中基本数据类型的包装类,是的基本数据类的变量具有类的特征

  2. 基本数据类型、包装类、String三者之间的转换

基本数据类型 包装类

byte Byte

short Short

int Interger

long Long

float Float

double Double

boolean Boolean

char Character

 

基本数据类型与包装类和String之间的转换

基本数据类型 -----> 包装类

        int num1 = 10;
       Integer integer = new Integer(num1);
       System.out.println(integer.toString());

       Integer integer1 = new Integer("123");
       System.out.println(integer1.toString());

       Integer integer1 = new Integer("123abc");
       System.out.println(integer1.toString());//报错

 

包装类 ------> 基本数据类型 调用xxxValue()

        Integer in1 = new Integer(12);
       int i = in1.intValue();
       
       Float f1 = new Float(12.3);
       float f2 = f1.floatValue();  

 

自动装箱

基本数据类型 -----> 包装类

int num2 = 10;
Integer in2 = num2;

 

自动拆箱

包装类 ------> 基本数据类型

int num3 = in2;

 

基本数据类型、包装类 -----> String类 调用String的valueOf()

 //方式一 int num1 = 10; 
String str1 = num1 + "";
//方式二:调用String的valueOf()
float f1 = 12.3f;
String str2 = String.valueOf(f1);

 

String类 ------> 基本数据类型、包装类 调用包装类的parseXxx()

可能会报NumberFormatException

String str1 = "123";
int i = Integer.parseInt(str1);

 

测试题

Integer i = new Integer(1);
Integer j = new Integer(1);
System.out.print1n(i == j);//false 比较的地址

//Integer内部定义了IntegerCache结构,工ntegerCache中定义了Integer[],
//保存了从-128~127范围的整数。如果我们使用自动装箱的方式,给Integer赋值的范围在
//-128~127范围内时,可以直接使用数组中的元素,不用再去new了。目的:提高效率
Integer m = 1;
Integer n = 1;
system.out.print1n(m == n); //true

Integer x = 128;//相当于new了一个Integer对象
Integer y = 128;
System.out.print1n(x ==y );//false

 

 

posted @   flypiggg  阅读(42)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示