Java基础(包装类)

包装类

概念:将基本数据类型封装成对象类型的类,就叫包装类(好处在于可以提供更多的操作基本数值的功能)。

Java提供了8种基本类型对应的包装类,如图所示:

将字符串转成基本类型:

注意:parseXXX(String s);其中XXX表示基本类型,参数为可以转成基本类型的字符串,如果字符串无法转成基本类型,将会发生数字转换的问题 NumberFormatException

将基本数值转成字符串有3种方式:

  1. 基本类型直接与””,相连接即可;34+""
  2. 调用String的valueOf方法;String.valueOf(34)

     3.调用包装类中的toString方法;Integer.toString(34);

JDK5特性:自动装箱拆箱

  1. 自动拆箱:对象转成基本数值
  2. 自动装箱:基本数值转成对象

Integer i = 4;//自动装箱。相当于Integer i = Integer.valueOf(4);

i = i + 5;//等号右边:将i对象转成基本数值(自动拆箱) i.intValue() + 5; 加法运算完成后,再次装箱,把基本数值转成对象

  1. 自动装箱(byte常量池)细节的演示

当数值在byte范围之内时,进行自动装箱,不会新创建对象空间而是使用原来已有的空间。

Integer a = new Integer(3);

Integer b = new Integer(3);

System.out.println(a==b);//false

System.out.println(a.equals(b));//true

Integer x = 127;

Integer y = 127;

//在jdk1.5自动装箱时,如果数值在byte范围之内,不会新创建对象空间而是使用原来已有的空间。

System.out.println(x==y); //true

System.out.println(x.equals(y)); //true

char提供了包装类Character类

常用方法:

1

isLetter() 是否是一个字母

2

isDigit():是否是一个数字字符

3

isWhitespace():是否是一个空白字符

4

isUpperCase():是否是大写字母

5

isLowerCase():是否是小写字母

6

toUpperCase():指定字母的大写形式

7

toLowerCase():指定字母的小写形式

8

toString():返回字符的字符串形式,字符串的长度仅为1

案例:统计各种字符串的个数

        int bigCount = 0;
        int smallCount = 0;
        int numberCount = 0;
        String s1= "wwwTTTcccyyy193yyy";
        // 把字符串转换为字符数组
        char[] chs = s1.toCharArray();
        // 遍历字符数组,获取每一个字符
        for (int x = 0; x < chs.length; x++) {
            // 判断该字符是
            if (Character.isUpperCase(chs[x])) {
                bigCount++;
            } else if (Character.isLowerCase(chs[x])) {
                smallCount++;
            } else if (Character.isDigit(chs[x])) {
                numberCount++;
            }
        }
        // 输出结果即可
        System.out.println("大写字符:" + bigCount + "个");
        System.out.println("小写字符:" + smallCount + "个");
        System.out.println("数字字符:" + numberCount + "个");
发布了75 篇原创文章 · 获赞 164 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_41679818/article/details/94204417