Java进阶之拆装箱&String常用方法

一、包装类

1.1 包装类概述

每一种基本类型都有其对应的引用类型,这个对应的引用类型叫做包装类。

基本类型基本类型包装类
byteByte
shortShort
intInteger(特殊)
longLong
floatFloat
doubleDouble
charCharacter (特殊)
booleanBoolean
  • 基本类型就是一些简单的数据,只能进行运算或直接使用,不能调用方法,功能比较简单。
  • 包装类是引用类型,可以创建对象,包装类不仅仅可以表示数据,也可以调用方法完成一些功能,功能强大。

基本类型和对应的包装类使用方式基本一致。

1.2 自动拆装箱

拆箱: 包装类类型转成对应的基本类型。

装箱: 基本类型转成对应的包装类类型。

JDK5的时候,多了一个新的特性,叫做自动拆装箱,有了自动拆装箱后,基本类型以及包装类类型可以自动转换。

public static void main(String[] args) {
        自动装箱:将基本类型的10赋值给Integer类型,基本类型会自动转成对应的包装类类型,是自动装箱。
        Integer a = 10;
        自动装箱:将基本类型的20赋值给Integer类型,基本类型会自动转成对应的包装类类型,是自动装箱。
        Integer b = 20;
        自动拆箱: 会先将Integer类型的a和b转成int类型的a和b然后进行加法运算,此时就是包装类转基本类型,就是自动拆箱。
        自动装箱: a和b相加的结果是int类型,将int类型的结果赋值给Integer类型的sum,基本类型会自动转成对应的包装类类型,自动装箱。
        Integer sum = a + b;
        System.out.println(sum);
    }

1.3 手动拆装箱

在JDK5之前,如果想要进行基本类型和对应的包装类之间的转换,需要使用手动拆装箱。

  • 手动装箱(int -> Integer)使用包装类的静态方法valueOf即可。
    static Integer valueOf(int i):接受一个int类型的数据,返回Integer类型的结果。
  • 手动拆箱(Integer -> int)使用包装类的方法intValue实现
    int intValue():将Integer对象转成int数字并返回

其他类型的手动拆装箱也是类似的方法。

public static void main(String[] args) {
        手动装箱(int -> Integer)
        int num = 10;int类型的变量转成对应的包装类类型
        Integer warpNum = Integer.valueOf(num);
        System.out.println(warpNum);

        手动拆箱(Integer -> intint basicNum = warpNum.intValue();
        System.out.println(basicNum);
    }

1.4 字符串和基本类型相互转换

基本类型 -> 字符串有两种方法:

  • 1.直接在这个基本类型的数据后面加上"" (推荐)
  • 2.使用String的静态方法valueOf实现
    static String valueOf(int i):将int数字转成字符串,并将字符串返回

字符串 -> 基本类型

可以使用基本类型对应包装类的静态方法parseXXX完成

  • 字符串 -> int类型,使用Integer中的静态方法parseInt完成
  • 字符串 -> double类型,使用Double中的静态方法parseDouble完成
public static void main(String[] args) {
        //基本类型 -> 字符串
        int num = 10;
        //直接在这个基本类型的数据后面加上""
        String str = 10 + "";
        System.out.println(str);
        
        //使用String的静态方法valueOf实现
        int num1 = 20;
        String str1 = String.valueOf(num1);
        System.out.println(str1);

        System.out.println("=================================");
        //字符串 -> 基本类型
        //定义一个字符串
        String s = "12345"; //如果字符串中不是纯数字,那么转成数字会报错
        //使用Integer中的静态方法parseInt将字符串转成int数字.
        int basicNum = Integer.parseInt(s);
        System.out.println(basicNum);
    }

1.5 关于自动拆装箱的面试题

为什么下列输出不一致?

public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;
        Integer c = 200;
        Integer d = 200;
        System.out.println(a==b);//true
        System.out.println(c==d);//false
    }

在自动装箱时会使用Integer valueOf(int i)方法,该方法有一个IntegerCache的缓存,缓存的区间为[-128,127],当i的值在这个区间时,都在这个缓存区间里面;当不在这个区间时,会重新开辟空间存放i,所以c和d地址值不同,结果为false。

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
}
private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

二、字符串常用API

2.1 concat

String concat(String str):对字符串进行拼接

public static void main(String[] args) {
        //定义一个字符串
        String str = "Hello";
        //在该字符串后面拼接World
        //String result = str + "World";
        String result = str.concat("World");
        System.out.println(result);//HelloWorld
    }

2.2 contains

boolean contains(String s):判断字符串中是否包含指定的内容

public static void main(String[] args) {
        //定义字符串
        String str = "I love Java and Java Teacher";
        //判断字符串中是否包含Java
        System.out.println(str.contains("Java"));//true
    }

2.3 startsWith & endsWith

  • boolean startsWith(String prefix):判断字符串是否以指定内容开头
  • boolean endsWith(String suffix):判断字符串是否以指定内容结尾
public static void main(String[] args) {
        String str = "王叔叔";
        //判断str字符串是否以王开头
        System.out.println("是否以王开头:" + str.startsWith("王"));//true
        System.out.println("是否以叔结尾:" + str.endsWith("叔"));//true
    }

2.4 indexOf & lastIndexOf

  • int indexOf(String str) 在字符串中查找指定内容第一次出现的索引位置,如果没有找到,返回-1
  • int lastIndexOf(String str) 在字符串中查找指定内容最后一次出现的索引,如果没有找到,返回-1
public static void main(String[] args) {
        String str = "I love Java and Java love me";
        System.out.println("love在字符串中第一次出现的索引:" + str.indexOf("love"));
        System.out.println("aini在字符串中第一次出现的索引:" + str.indexOf("aini"));
        System.out.println("love在字符串中最后一次出现的索引:" + str.lastIndexOf("love"));
}

2.5 toCharArray

char[] toCharArray() 将字符串转成一个字符数组并返回

public static void main(String[] args) {
        //定义字符串
        String str = "hello";
        //将字符串转成字符数组
        char[] cArr = str.toCharArray();
        //遍历
        for (int i = 0; i < cArr.length; i++) {
            System.out.println(cArr[i]);
        }
    }

2.6 toLowerCase & toUpperCase

  • String toLowerCase() 将字符串的内容全部转小写并返回
  • String toUpperCase() 将字符串的内容全部转大写并返回
public static void main(String[] args) {
        //定义字符串
        String str = "HelloWorld";
        //将字符串全部转小写
        String lowerStr = str.toLowerCase();
        //输出结果
        System.out.println(lowerStr);
        //将字符串全部转大写
        String upperStr = str.toUpperCase();
        System.out.println(upperStr);
    }

2.7 trim

String trim() 去除字符串的两边的空格,会将去除空格之后的结果返回

public static void main(String[] args) {
        //定义字符串
        String str = "   Hello   World    ";
        //去除空格
        String result = str.trim();
        //输出
        System.out.println(result);//Hello World
    }

2.8 split

String[] split(String regex) 对字符串根据指定内容进行切割,返回字符串数组

public static void main(String[] args) {
        //定义字符串
        String str = "西瓜,茄子,香蕉";
        //使用split方法切割字符串
        String[] strArr = str.split(",");
        //遍历字符串数组
        for (int i = 0; i < strArr.length; i++) {
            System.out.println(strArr[i]);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值