1.String类型 —>基本数据类型、包装类:调用包装类的parseXxx(String s)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14@Test public void test5(){ String str1 = "123"; //错误的情况: //int num1 = (int)str1; //Integer in1 = (Integer)str1; //可能会报NumberFormatException int num2 = Integer.parseInt(str1); System.out.println(num2 + 1); String str2 = "true1"; boolean b1 = Boolean.parseBoolean(str2); System.out.println(b1); }
2.基本数据类型、包装类—>String类型:调用String重载的valueOf(Xxx xxx)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14@Test public void test4(){ int num1 = 10; //方式1:连接运算 String str1 = num1 + ""; //方式2:调用String的valueOf(Xxx xxx) float f1 = 12.3f; String str2 = String.valueOf(f1);//"12.3" Double d1 = new Double(12.4); String str3 = String.valueOf(d1); System.out.println(str2); System.out.println(str3);//"12.4" }
3.包装类—>基本数据类型:调用包装类Xxx的xxxValue()
复制代码
1
2
3
4
5
6
7
8
9
10@Test public void test2(){ Integer in1 = new Integer(12); int i1 = in1.intValue(); System.out.println(i1 + 1); Float f1 = new Float(12.3); float f2 = f1.floatValue(); System.out.println(f2 + 1); }
4.基本数据类型 —>包装类:调用包装类的构造器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27@Test public void test1(){ int num1 = 10; //System.out.println(num1.toString()); Integer in1 = new Integer(num1); System.out.println(in1.toString()); Integer in2 = new Integer("123"); System.out.println(in2.toString()); //报异常 // Integer in3 = new Integer("123abc"); // System.out.println(in3.toString()); Float f1 = new Float(12.3f); Float f2 = new Float("12.3"); System.out.println(f1); System.out.println(f2); Boolean b1 = new Boolean(true); Boolean b2 = new Boolean("TrUe"); System.out.println(b2); Boolean b3 = new Boolean("true123"); System.out.println(b3);//false Order order = new Order(); System.out.println(order.isMale);//false System.out.println(order.isFemale);//null }
复制代码
1
2
3
4
5class Order{ boolean isMale; Boolean isFemale; }
JDK 5.0 新特性:自动装箱 与自动拆箱
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18@Test public void test3(){ // int num1 = 10; // //基本数据类型-->包装类的对象 // method(num1); //自动装箱:基本数据类型 --->包装类 int num2 = 10; Integer in1 = num2;//自动装箱 boolean b1 = true; Boolean b2 = b1;//自动装箱 //自动拆箱:包装类--->基本数据类型 System.out.println(in1.toString()); int num3 = in1;//自动拆箱 }
后记
1.为什么要有包装类(或封装类)?
为了使基本数据类型的变量具有类的特征,引入包装类。
2.基本数据类型与对应的包装类:
3.需要掌握的类型间的转换:(基本数据类型、包装类、String)
4.简易速记
- 基本数据类型<—>包装类:------------JDK 5.0 新特性:自动装箱 与自动拆箱
- 基本数据类型、包装类—>String:------调用String重载的valueOf(Xxx xxx)
- String—>基本数据类型、包装类:------调用包装类的parseXxx(String s)
注意:转换时,可能会报NumberFormatException
说明
- Object类中定义的equals()和==的作用是相同的:比较两个对象的地址值是否相同.即两个引用是否指向同一个对象实体
- 像String、Date、File、包装类等都【重写】了Object类中的equals()方法。
- 重写以后,比较的不是 两个引用的地址是否相同,而是比较两个对象的"实体内容"是否相同。
最后
以上就是平淡大象最近收集整理的关于基本数据类型、包装类、String三者之间的相互转换JDK 5.0 新特性:自动装箱 与自动拆箱的全部内容,更多相关基本数据类型、包装类、String三者之间的相互转换JDK内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复