Java基础案例教程 第五章JavaAPI———5.4 包装类

一、包装类基本概念

  • 表中,列举了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);
		}
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值