了解java的包装类

1,Java包装类
在这里插入图片描述 包装类主要提供了两类方法:

1、进行多个类型之间的转换

2、将字符串和本类型及包装类相互转换
在这里插入图片描述
实例,先将int类型转为包装类,在通过包装类中的方法转成其他类
public class HelloWorld {
public static void main(String[] args) {

     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);
 }

}
上述为基本类型转为包装类,为装箱操作,分为手动装箱与自动装箱
然,包装类也可转为基本类型,即为拆箱,分为手动拆箱与自动拆箱
简例:
public class HelloWorld {
public static void main(String[] args) {
double a = 91.5;

      // double类型手动装箱
     Double b = new Double(a);    
     
     // double类型自动装箱
     Double c = a;  

     System.out.println("装箱后的结果为:" + b + "和" + c);

     Double d = new Double(87.0);
     
     // Double包装类对象手动拆箱
     double e = d.doubleValue();
     
     //Double包装类对象自动拆箱
     double f = d;
     
      System.out.println("拆箱后的结果为:" + e + "和" + f);
 }

}

发布了15 篇原创文章 · 获赞 3 · 访问量 375

猜你喜欢

转载自blog.csdn.net/weixin_44520602/article/details/105088620