java包装类,自动装箱,拆箱,以及基本数据类型与字符串的转换

时间:2019-09-08
本文章向大家介绍java包装类,自动装箱,拆箱,以及基本数据类型与字符串的转换,主要包括java包装类,自动装箱,拆箱,以及基本数据类型与字符串的转换使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 1 package cn.learn;
 2 
 3 import java.util.ArrayList;
 4 
 5 /*
 6 包装类 java.lang中,基本运算类型效率高
 7 装箱:把基本类型数据包装为包装类
 8     1.构造方法
 9     Integer i = new Integer(可以是int,也可以是String的整数值)
10 拆箱:在包装类中取出基本类型
11 
12 基本类型与字符串类型的相互转换
13 基本类型->字符串,返回一个字符串
14     1.基本类型值+""(空字符串)
15     2.包装类的静态方法toString,是Object的toString重载,不是一个东西
16     3.String类的 static String valueOf(int i)
17 字符串->基本类型,返回一个基本数据类型
18     1.使用包装类的parseXXX("数值类型的字符串")
19         eg:Integer类 : static int parseInt("数值")
20 
21  */
22 public class WrapperClass {
23     public static void main(String[] args) {
24 
25         //构造方法-过时
26         Integer num =new Integer(1);  //1
27         Integer num01 =new Integer("1");  //1
28 
29         //拆箱
30         int num02 =num.intValue();   //1
31 
32         //自动装箱
33         Integer num03 = 5;
34         //Integer num04 = "5";报错
35         ArrayList<Integer> list = new ArrayList<>();
36         //自动装箱,实际上是list.add(new Integer(1))
37         list.add(1);
38 
39         //自动拆箱,实际上,是num03.valueOf()+2;
40         int num04 = num03 +2; //7
41         System.out.println(num04);
42         //ArrayList的自动拆箱
43         int i = list.get(0); //1
44 
45         //基本类型->字符串
46         String str= 66+"";  //"66"  66
47         String str0=Integer.toString(500);  //返回的是一个字符串 "500"  500
48         String str1=String.valueOf(55);  //"55"  55
49         System.out.println(str+str0+str1);  //6650055
50 
51         //字符串->基本类型
52         int p1=Integer.parseInt("55");  //需要是int数值
53         System.out.println(p1+2);  //57
54         int p2=(int)'a';
55         System.out.println(p2); //97
56 
57 
58 
59     }
60 
61 }

原文地址:https://www.cnblogs.com/huxiaobai/p/11488854.html