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

 1 /**
 2  * 基本数据类型与包装类,String类型的三者转换
 3  *
 4  *
 5  */
 6 
 7 public class Demo3 {
 8     public static void main(String[] args) {
 9 
10         Integer i=new Integer(15);
11         System.out.println(i);
12         System.out.println(i.intValue());
13 
14     }
15     //String类型与基本数据类型和包装类的相互转换
16     @Test
17     public void add2(){
18         //方式1:连接运算
19         int sum=1;
20         String name=sum+"";
21         System.out.println(name);
22         //方式2:使用String.valueOf()方法
23         float sum2=12.3f;
24         String string=String.valueOf(sum2);
25         System.out.println( string);
26         //String类型转换成基本,包装类
27         String hp="true";
28         String hpp="123";
29 
30         System.out.println(Integer.parseInt(hpp));//Integer.parseInt()方法进行转换;
31         System.out.println(Boolean.parseBoolean(hp));
32         
33     }
34     @Test
35    public void add(){
36        Integer i=new Integer(17);//基本数据类型转换成包装类
37        int b=i.intValue();//包装类转换成基本数据类型
38        System.out.println(i);
39        System.out.println(i.intValue());
40        Boolean is=new Boolean(true);
41         System.out.println(is);
42         Integer in=new Integer(18);//将基本数据类型转换成包装类放入方法形参中,多态性的体现
43         sum(in);
44         int c=15;
45         Integer integer=c;//将c直接赋值给Integer类型叫做自动装箱,不用再去创建Integer类的对象调用构造器
46         int d=integer;//将包装类变成基本数据类型,叫做自动拆箱
47     }
48 public void sum(Object object){
49     System.out.println(object);
50 }
51 }

 

posted @ 2021-09-17 22:38  tiiiiii  阅读(68)  评论(0)    收藏  举报