一、包装类基本概念
- 表中,列举了8种数据类型及其对应的包装类。其中,除了Interger和Characterc其他包装类的名称和基本数据类型的名称一致,只是类名的第一个字母要大写
二、装箱和拆箱
包装类和基本数据类型在进行转换时,引入了装箱拆箱的概念,其中装箱是指将基本数据类型的值转为引用数据类型,反之,拆箱是指将引用数据类型的对象转为基本数据类型
1、装箱 int---> Integer
通过构造方法,完成装箱操作
Integer(int n)
package cn.itcast.chapter05.example19;
/**
* 装箱
*/
public class Example19 {
public static void main(String args[]) {
int a = 20;
Integer in = new Integer(a);
System.out.println(in);
}
}
输出:
20
2、拆箱 Integer --->int
Integer类的方法: public int intValue() 以int类型返回该Integer的值
package cn.itcast.chapter05.example20;
/**
* 拆箱操作
* intValue()方法的使用
*/
public class Example20 {
public static void main(String args[]) {
Integer num = new Integer(20);
int a = 10;
int sum = num.intValue() + a;
System.out.println("sum=" + sum);
}
}
输出:
sun=30
3、String--->int
Integer类的方法:public static int parseInt(String s)
package cn.itcast.chapter05.example21;
/**
* parseInt()方法的使用,在屏幕上打印*矩形
*/
public class Example21 {
public static void main(String args[]) {
int w = Integer.parseInt("20");
int h = Integer.parseInt("10");
for (int i = 0; i < h; i++) {
StringBuffer sb = new StringBuffer();
for (int j = 0; j < w; j++) {
sb.append("*");
}
System.out.println(sb.toString()); //或者 println(sb);
}
}
}