基本类型包装类的基本使用

基本类型包装类的基本使用:实现字符串与基本数据之间转换

基本类型包装类作用:实现字符串与基本数据之间转换
8种基本类型对应的包装类如下:
其中需要注意int对应的是Integerchar对应的Character,其他6个都是基本类型首字母大写即可。
8种基本类型对应的包装类如下:在这里插入图片描述
字符串转基本类型

String a="12345";
		int a1=Integer.parseInt(a);
		int math=a1+1;
		System.out.println(math);//字符串转基本类型
结果:12346

基本类型转字符串

int b=4567;
		String b1=String.valueOf(b);
		String b2=Integer.toString(b);
		System.out.println((b1+8)+","+(b2+9));//基本类型转字符串
结果:45678,45679

基本数值转换包装对象
1.使用构造函数实现

int c=789;
		String d="666";
		Integer c1=new Integer(c);
		Integer d1=new Integer(d);//使用构造函数实现--基本数值转换包装对象

2.使用包装类valueof方法实现

Integer c2=Integer.valueOf(c);
		Integer d2=Integer.valueOf(d);//使用包装类valueof方法实现--基本数值转换包装对象
		int d3=d2.intValue();
		System.out.println((d1+1)+","+(d2+2)+","+(d3-1));
结果:667,668,665

自动装箱自动拆箱

int e=778;
		Integer x=e;//相当于Integer.valueOf(e);----自动装箱过程
		x=x+1;//相当于x转换为基本数值(自动拆箱过程)x.intValue()+1;加法运算完后再自动装箱,把基本数值转换成为对象

注意:

Integer f=100;
		Integer g=100;
		System.out.println((f==g)+","+(f.equals(g)));//数值<128,为了节约内存空间,指向的是同一个对象。
		Integer f1=200;
		Integer g1=200;
		System.out.println((f1==g1)+","+(f1.equals(g1)));//数值>128分别指向自己创建的对象,
		Integer f2=new Integer(100);
		Integer g2=new Integer(100);
		System.out.println((f2==g2)+","+(f2.equals(g2)));//数值虽然小于128但是使用的是new Integer()直接创建的新的对象
结果:	true,true
		false,true
		false,true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值