java-包装类

1、包装类:

序号基本数据类型引用数据类型
1byteByte
2shortShort
3intInteger
4longLong
5floatFloat
6doubleDouble
7charCharacter
8booleanBoolean

2、包装类的概念

基本数据类型的数据使用起来非常方便,但是,没有对应的方法来操作这些数据,所以我们可以不使用一个类,把基本数据类型的数据包装起来,这个类就叫做包装类,在包装类中定义了一些方法,用来操作这些基本数据类型的数据。

3、装箱与拆箱

装箱指:将一个基本数据类型的值包装到包装类中,基本数据类型 ---->包装类;

拆箱指:在包装类中取出基本数据类型:包装类 —> 基本数据类型;

装箱一般使用  包装类.valueOf(value)方法

拆箱一般使用:value.intValue();
package demo02.demo_Integer;

public class Demo01Integer {

    public static void main(String[] args) {

        //装箱:
        int a = 20;
        Integer c1 = Integer.valueOf(a);
        Integer c2 = Integer.valueOf("20");

        System.out.println(c1);  //20
        System.out.println(c2);   //20

        //拆箱
        Integer in = 30;
        int inte = in.intValue();
        System.out.println(inte);    //30
    }
}

20
20
30

4、自动装箱与自动拆箱:

自动装箱,就是指:直接可以将基本数据类型转化为包装类;

自动拆箱:就是指:直接可以将包装类转化为基本数据类型;

前提条件:jdk1.5之后

package demo02.demo_Integer;

import java.util.ArrayList;

public class Demo02Integer {

    public static void main(String[] args) {

        //自动装箱:
        int c = 20;
        Integer integer1 = c;
        System.out.println(integer1);

        //自动拆箱
        Integer integer2 = 30;
        int c2 = integer2;

        //一般用法1;
        Integer in = 2;
        //含义:因为Integer类型的数据不能直接运算,首先将“in”转化为int类型,实现自动拆箱,之后,将计算出来的结果3,实现自动装箱,因为‘in的数据类型为Integer类型
        in = in + 1;

        //一般用法2:
        ArrayList<Integer> list = new ArrayList<>();
        list.add(2);    //自动装箱:将int 类型的数据2 装箱为Integer类型,
        int i = list.get(0);    //自动拆箱, list.get(0);返回的数据类型为Intefer类型,
    }
}

5、基本类型与字符串之间的转换

基本类型转化为字符串(以int类型为例)

String str = 100 + "";    //最常用的方法
int a = 20;
String str = Integer.toString(a);
int a = 10;
String str = String.valueOf(a);

字符串转化为基本数据类型:

int s = Integer.parseInt("10")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值